1   /*
2    *  Licensed to the Apache Software Foundation (ASF) under one
3    *  or more contributor license agreements.  See the NOTICE file
4    *  distributed with this work for additional information
5    *  regarding copyright ownership.  The ASF licenses this file
6    *  to you under the Apache License, Version 2.0 (the
7    *  "License"); you may not use this file except in compliance
8    *  with the License.  You may obtain a copy of the License at
9    *
10   *    http://www.apache.org/licenses/LICENSE-2.0
11   *
12   *  Unless required by applicable law or agreed to in writing,
13   *  software distributed under the License is distributed on an
14   *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   *  KIND, either express or implied.  See the License for the
16   *  specific language governing permissions and limitations
17   *  under the License.
18   */
19  package org.codehaus.groovy.runtime;
20  
21  import groovy.io.FileType;
22  import groovy.io.GroovyPrintWriter;
23  import groovy.lang.*;
24  import groovy.transform.stc.ClosureParams;
25  import groovy.transform.stc.FirstParam;
26  import groovy.transform.stc.FromString;
27  import groovy.transform.stc.MapEntryOrKeyValue;
28  import groovy.transform.stc.SimpleType;
29  import groovy.util.ClosureComparator;
30  import groovy.util.GroovyCollections;
31  import groovy.util.MapEntry;
32  import groovy.util.OrderBy;
33  import groovy.util.PermutationGenerator;
34  import groovy.util.ProxyGenerator;
35  import org.codehaus.groovy.classgen.Verifier;
36  import org.codehaus.groovy.reflection.ClassInfo;
37  import org.codehaus.groovy.reflection.MixinInMetaClass;
38  import org.codehaus.groovy.reflection.ReflectionCache;
39  import org.codehaus.groovy.reflection.stdclasses.CachedSAMClass;
40  import org.codehaus.groovy.runtime.callsite.BooleanClosureWrapper;
41  import org.codehaus.groovy.runtime.callsite.BooleanReturningMethodInvoker;
42  import org.codehaus.groovy.runtime.dgmimpl.NumberNumberDiv;
43  import org.codehaus.groovy.runtime.dgmimpl.NumberNumberMinus;
44  import org.codehaus.groovy.runtime.dgmimpl.NumberNumberMultiply;
45  import org.codehaus.groovy.runtime.dgmimpl.NumberNumberPlus;
46  import org.codehaus.groovy.runtime.dgmimpl.arrays.*;
47  import org.codehaus.groovy.runtime.metaclass.MetaClassRegistryImpl;
48  import org.codehaus.groovy.runtime.metaclass.MissingPropertyExceptionNoStack;
49  import org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation;
50  import org.codehaus.groovy.runtime.typehandling.GroovyCastException;
51  import org.codehaus.groovy.runtime.typehandling.NumberMath;
52  import org.codehaus.groovy.tools.RootLoader;
53  import org.codehaus.groovy.transform.trait.Traits;
54  import org.codehaus.groovy.util.ArrayIterator;
55  
56  import java.io.*;
57  import java.lang.reflect.Array;
58  import java.lang.reflect.Field;
59  import java.lang.reflect.Method;
60  import java.lang.reflect.Modifier;
61  import java.lang.reflect.Proxy;
62  import java.math.BigDecimal;
63  import java.math.BigInteger;
64  import java.net.MalformedURLException;
65  import java.net.ServerSocket;
66  import java.net.Socket;
67  import java.net.URI;
68  import java.net.URISyntaxException;
69  import java.net.URL;
70  import java.security.AccessController;
71  import java.security.PrivilegedAction;
72  import java.text.MessageFormat;
73  import java.util.*;
74  import java.util.concurrent.BlockingQueue;
75  import java.util.logging.Logger;
76  import java.util.regex.Matcher;
77  import java.util.regex.Pattern;
78  
79  /**
80   * This class defines new groovy methods which appear on normal JDK
81   * classes inside the Groovy environment. Static methods are used with the
82   * first parameter being the destination class,
83   * i.e. <code>public static String reverse(String self)</code>
84   * provides a <code>reverse()</code> method for <code>String</code>.
85   * <p>
86   * NOTE: While this class contains many 'public' static methods, it is
87   * primarily regarded as an internal class (its internal package name
88   * suggests this also). We value backwards compatibility of these
89   * methods when used within Groovy but value less backwards compatibility
90   * at the Java method call level. I.e. future versions of Groovy may
91   * remove or move a method call in this file but would normally
92   * aim to keep the method available from within Groovy.
93   *
94   * @author <a href="mailto:james@coredevelopers.net">James Strachan</a>
95   * @author Jeremy Rayner
96   * @author Sam Pullara
97   * @author Rod Cope
98   * @author Guillaume Laforge
99   * @author John Wilson
100  * @author Hein Meling
101  * @author Dierk Koenig
102  * @author Pilho Kim
103  * @author Marc Guillemot
104  * @author Russel Winder
105  * @author bing ran
106  * @author Jochen Theodorou
107  * @author Paul King
108  * @author Michael Baehr
109  * @author Joachim Baumann
110  * @author Alex Tkachman
111  * @author Ted Naleid
112  * @author Brad Long
113  * @author Jim Jagielski
114  * @author Rodolfo Velasco
115  * @author jeremi Joslin
116  * @author Hamlet D'Arcy
117  * @author Cedric Champeau
118  * @author Tim Yates
119  * @author Dinko Srkoc
120  * @author Andre Steingress
121  * @author Yu Kobayashi
122  */
123 public class DefaultGroovyMethods extends DefaultGroovyMethodsSupport {
124 
125     private static final Logger LOG = Logger.getLogger(DefaultGroovyMethods.class.getName());
126     private static final Integer ONE = 1;
127     private static final BigInteger BI_INT_MAX = BigInteger.valueOf(Integer.MAX_VALUE);
128     private static final BigInteger BI_INT_MIN = BigInteger.valueOf(Integer.MIN_VALUE);
129     private static final BigInteger BI_LONG_MAX = BigInteger.valueOf(Long.MAX_VALUE);
130     private static final BigInteger BI_LONG_MIN = BigInteger.valueOf(Long.MIN_VALUE);
131 
132     public static final Class [] additionals = {
133             NumberNumberPlus.class,
134             NumberNumberMultiply.class,
135             NumberNumberMinus.class,
136             NumberNumberDiv.class,
137             ObjectArrayGetAtMetaMethod.class,
138             ObjectArrayPutAtMetaMethod.class,
139             BooleanArrayGetAtMetaMethod.class,
140             BooleanArrayPutAtMetaMethod.class,
141             ByteArrayGetAtMetaMethod.class,
142             ByteArrayPutAtMetaMethod.class,
143             CharacterArrayGetAtMetaMethod.class,
144             CharacterArrayPutAtMetaMethod.class,
145             ShortArrayGetAtMetaMethod.class,
146             ShortArrayPutAtMetaMethod.class,
147             IntegerArrayGetAtMetaMethod.class,
148             IntegerArrayPutAtMetaMethod.class,
149             LongArrayGetAtMetaMethod.class,
150             LongArrayPutAtMetaMethod.class,
151             FloatArrayGetAtMetaMethod.class,
152             FloatArrayPutAtMetaMethod.class,
153             DoubleArrayGetAtMetaMethod.class,
154             DoubleArrayPutAtMetaMethod.class,
155     };
156 
157     public static final Class[] DGM_LIKE_CLASSES = new Class[]{
158             DefaultGroovyMethods.class,
159             DateGroovyMethods.class,
160             EncodingGroovyMethods.class,
161             IOGroovyMethods.class,
162             ProcessGroovyMethods.class,
163             ResourceGroovyMethods.class,
164             SocketGroovyMethods.class,
165             StringGroovyMethods.class//,
166             // TODO provide alternative way for these to be registered
167 //            SqlGroovyMethods.class,
168 //            SwingGroovyMethods.class,
169 //            XmlGroovyMethods.class,
170 //            NioGroovyMethods.class
171     };
172     private static final Object[] EMPTY_OBJECT_ARRAY = new Object[0];
173 
174     /**
175      * Identity check. Since == is overridden in Groovy with the meaning of equality
176      * we need some fallback to check for object identity.  Invoke using the
177      * 'is' method, like so: <code>def same = this.is(that)</code>
178      *
179      * @param self  an object
180      * @param other an object to compare identity with
181      * @return true if self and other are both references to the same
182      *         instance, false otherwise
183      * @since 1.0
184      */
185     public static boolean is(Object self, Object other) {
186         return self == other;
187     }
188 
189     /**
190      * Allows the closure to be called for the object reference self.
191      * Synonym for 'with()'.
192      *
193      * @param self    the object to have a closure act upon
194      * @param closure the closure to call on the object
195      * @return result of calling the closure
196      * @since 1.0
197      */
198     public static <T> T identity(Object self, Closure<T> closure) {
199         return DefaultGroovyMethods.with(self, closure);
200     }
201 
202     /**
203      * Allows the closure to be called for the object reference self.
204      * <p>
205      * Any method invoked inside the closure will first be invoked on the
206      * self reference. For instance, the following method calls to the append()
207      * method are invoked on the StringBuilder instance:
208      * <pre>
209      * def b = new StringBuilder().with {
210      *   append('foo')
211      *   append('bar')
212      *   return it
213      * }
214      * assert b.toString() == 'foobar'
215      * </pre>
216      * This is commonly used to simplify object creation, such as this example:
217      * <pre>
218      * def p = new Person().with {
219      *   firstName = 'John'
220      *   lastName = 'Doe'
221      *   return it
222      * }
223      * </pre>
224      *
225      * @param self    the object to have a closure act upon
226      * @param closure the closure to call on the object
227      * @return result of calling the closure
228      * @since 1.5.0
229      */
230     public static <T,U> T with(
231             @DelegatesTo.Target("self") U self,
232             @DelegatesTo(value=DelegatesTo.Target.class,
233                     target="self",
234                     strategy=Closure.DELEGATE_FIRST)
235             @ClosureParams(FirstParam.class)
236             Closure<T> closure) {
237         @SuppressWarnings("unchecked")
238         final Closure<T> clonedClosure = (Closure<T>) closure.clone();
239         clonedClosure.setResolveStrategy(Closure.DELEGATE_FIRST);
240         clonedClosure.setDelegate(self);
241         return clonedClosure.call(self);
242     }
243 
244     /**
245      * Allows the subscript operator to be used to lookup dynamic property values.
246      * <code>bean[somePropertyNameExpression]</code>. The normal property notation
247      * of groovy is neater and more concise but only works with compile-time known
248      * property names.
249      *
250      * @param self     the object to act upon
251      * @param property the property name of interest
252      * @return the property value
253      * @since 1.0
254      */
255     public static Object getAt(Object self, String property) {
256         return InvokerHelper.getProperty(self, property);
257     }
258 
259     /**
260      * Allows the subscript operator to be used to set dynamically named property values.
261      * <code>bean[somePropertyNameExpression] = foo</code>. The normal property notation
262      * of groovy is neater and more concise but only works with property names which
263      * are known at compile time.
264      *
265      * @param self     the object to act upon
266      * @param property the name of the property to set
267      * @param newValue the value to set
268      * @since 1.0
269      */
270     public static void putAt(Object self, String property, Object newValue) {
271         InvokerHelper.setProperty(self, property, newValue);
272     }
273 
274     /**
275      * Generates a detailed dump string of an object showing its class,
276      * hashCode and fields.
277      *
278      * @param self an object
279      * @return the dump representation
280      * @since 1.0
281      */
282     public static String dump(Object self) {
283         if (self == null) {
284             return "null";
285         }
286         StringBuilder buffer = new StringBuilder("<");
287         Class klass = self.getClass();
288         buffer.append(klass.getName());
289         buffer.append("@");
290         buffer.append(Integer.toHexString(self.hashCode()));
291         boolean groovyObject = self instanceof GroovyObject;
292 
293         /*jes this may be rewritten to use the new getProperties() stuff
294          * but the original pulls out private variables, whereas getProperties()
295          * does not. What's the real use of dump() here?
296          */
297         while (klass != null) {
298             for (final Field field : klass.getDeclaredFields()) {
299                 if ((field.getModifiers() & Modifier.STATIC) == 0) {
300                     if (groovyObject && field.getName().equals("metaClass")) {
301                         continue;
302                     }
303                     AccessController.doPrivileged(new PrivilegedAction() {
304                         public Object run() {
305                             field.setAccessible(true);
306                             return null;
307                         }
308                     });
309                     buffer.append(" ");
310                     buffer.append(field.getName());
311                     buffer.append("=");
312                     try {
313                         buffer.append(InvokerHelper.toString(field.get(self)));
314                     } catch (Exception e) {
315                         buffer.append(e);
316                     }
317                 }
318             }
319 
320             klass = klass.getSuperclass();
321         }
322 
323         /* here is a different implementation that uses getProperties(). I have left
324          * it commented out because it returns a slightly different list of properties;
325          * i.e. it does not return privates. I don't know what dump() really should be doing,
326          * although IMO showing private fields is a no-no
327          */
328         /*
329         List props = getProperties(self);
330             for(Iterator itr = props.keySet().iterator(); itr.hasNext(); ) {
331             String propName = itr.next().toString();
332 
333             // the original skipped this, so I will too
334             if(pv.getName().equals("class")) continue;
335             if(pv.getName().equals("metaClass")) continue;
336 
337             buffer.append(" ");
338             buffer.append(propName);
339             buffer.append("=");
340             try {
341                 buffer.append(InvokerHelper.toString(props.get(propName)));
342             }
343             catch (Exception e) {
344                 buffer.append(e);
345             }
346         }
347         */
348 
349         buffer.append(">");
350         return buffer.toString();
351     }
352 
353     /**
354      * Retrieves the list of {@link groovy.lang.MetaProperty} objects for 'self' and wraps it
355      * in a list of {@link groovy.lang.PropertyValue} objects that additionally provide
356      * the value for each property of 'self'.
357      *
358      * @param self the receiver object
359      * @return list of {@link groovy.lang.PropertyValue} objects
360      * @see groovy.util.Expando#getMetaPropertyValues()
361      * @since 1.0
362      */
363     public static List<PropertyValue> getMetaPropertyValues(Object self) {
364         MetaClass metaClass = InvokerHelper.getMetaClass(self);
365         List<MetaProperty> mps = metaClass.getProperties();
366         List<PropertyValue> props = new ArrayList<PropertyValue>(mps.size());
367         for (MetaProperty mp : mps) {
368             props.add(new PropertyValue(self, mp));
369         }
370         return props;
371     }
372 
373     /**
374      * Convenience method that calls {@link #getMetaPropertyValues(java.lang.Object)}(self)
375      * and provides the data in form of simple key/value pairs, i.e.&nsbp;without
376      * type() information.
377      *
378      * @param self the receiver object
379      * @return meta properties as Map of key/value pairs
380      * @since 1.0
381      */
382     public static Map getProperties(Object self) {
383         List<PropertyValue> metaProps = getMetaPropertyValues(self);
384         Map<String, Object> props = new LinkedHashMap<String, Object>(metaProps.size());
385 
386         for (PropertyValue mp : metaProps) {
387             try {
388                 props.put(mp.getName(), mp.getValue());
389             } catch (Exception e) {
390                 LOG.throwing(self.getClass().getName(), "getProperty(" + mp.getName() + ")", e);
391             }
392         }
393         return props;
394     }
395 
396     /**
397      * Scoped use method
398      *
399      * @param self          any Object
400      * @param categoryClass a category class to use
401      * @param closure       the closure to invoke with the category in place
402      * @return the value returned from the closure
403      * @since 1.0
404      */
405     public static <T> T use(Object self, Class categoryClass, Closure<T> closure) {
406         return GroovyCategorySupport.use(categoryClass, closure);
407     }
408 
409     /**
410      * Extend object with category methods.
411      * All methods for given class and all super classes will be added to the object.
412      *
413      * @param self          any Class
414      * @param categoryClasses a category classes to use
415      * @since 1.6.0
416      */
417     public static void mixin(MetaClass self, List<Class> categoryClasses) {
418         MixinInMetaClass.mixinClassesToMetaClass(self, categoryClasses);
419     }
420 
421     /**
422      * Extend class globally with category methods.
423      * All methods for given class and all super classes will be added to the class.
424      *
425      * @param self          any Class
426      * @param categoryClasses a category classes to use
427      * @since 1.6.0
428      */
429     public static void mixin(Class self, List<Class> categoryClasses) {
430         mixin(getMetaClass(self), categoryClasses);
431     }
432 
433     /**
434      * Extend class globally with category methods.
435      *
436      * @param self          any Class
437      * @param categoryClass a category class to use
438      * @since 1.6.0
439      */
440     public static void mixin(Class self, Class categoryClass) {
441         mixin(getMetaClass(self), Collections.singletonList(categoryClass));
442     }
443 
444     /**
445      * Extend class globally with category methods.
446      *
447      * @param self          any Class
448      * @param categoryClass a category class to use
449      * @since 1.6.0
450      */
451     public static void mixin(Class self, Class[] categoryClass) {
452         mixin(getMetaClass(self), Arrays.asList(categoryClass));
453     }
454 
455     /**
456      * Extend class globally with category methods.
457      *
458      * @param self          any Class
459      * @param categoryClass a category class to use
460      * @since 1.6.0
461      */
462     public static void mixin(MetaClass self, Class categoryClass) {
463         mixin(self, Collections.singletonList(categoryClass));
464     }
465 
466     /**
467      * Extend class globally with category methods.
468      *
469      * @param self          any Class
470      * @param categoryClass a category class to use
471      * @since 1.6.0
472      */
473     public static void mixin(MetaClass self, Class[] categoryClass) {
474         mixin(self, Arrays.asList(categoryClass));
475     }
476 
477     /**
478      * Scoped use method with list of categories.
479      *
480      * @param self              any Object
481      * @param categoryClassList a list of category classes
482      * @param closure           the closure to invoke with the categories in place
483      * @return the value returned from the closure
484      * @since 1.0
485      */
486     public static <T> T use(Object self, List<Class> categoryClassList, Closure<T> closure) {
487         return GroovyCategorySupport.use(categoryClassList, closure);
488     }
489 
490     /**
491      * Allows the usage of addShutdownHook without getting the runtime first.
492      *
493      * @param self    the object the method is called on (ignored)
494      * @param closure the shutdown hook action
495      * @since 1.5.0
496      */
497     public static void addShutdownHook(Object self, Closure closure) {
498         Runtime.getRuntime().addShutdownHook(new Thread(closure));
499     }
500 
501     /**
502      * Allows you to use a list of categories, specifying the list as varargs.
503      * <code>use(CategoryClass1, CategoryClass2) { ... }</code>
504      * This method saves having to wrap the the category
505      * classes in a list.
506      *
507      * @param self  any Object
508      * @param array a list of category classes and a Closure
509      * @return the value returned from the closure
510      * @since 1.0
511      */
512     public static Object use(Object self, Object[] array) {
513         if (array.length < 2)
514             throw new IllegalArgumentException(
515                     "Expecting at least 2 arguments, a category class and a Closure");
516         Closure closure;
517         try {
518             closure = (Closure) array[array.length - 1];
519         } catch (ClassCastException e) {
520             throw new IllegalArgumentException("Expecting a Closure to be the last argument");
521         }
522         List<Class> list = new ArrayList<Class>(array.length - 1);
523         for (int i = 0; i < array.length - 1; ++i) {
524             Class categoryClass;
525             try {
526                 categoryClass = (Class) array[i];
527             } catch (ClassCastException e) {
528                 throw new IllegalArgumentException("Expecting a Category Class for argument " + i);
529             }
530             list.add(categoryClass);
531         }
532         return GroovyCategorySupport.use(list, closure);
533     }
534 
535     /**
536      * Print a value formatted Groovy style to self if it
537      * is a Writer, otherwise to the standard output stream.
538      *
539      * @param self  any Object
540      * @param value the value to print
541      * @since 1.0
542      */
543     public static void print(Object self, Object value) {
544         // we won't get here if we are a PrintWriter
545         if (self instanceof Writer) {
546             try {
547                 ((Writer) self).write(InvokerHelper.toString(value));
548             } catch (IOException e) {
549                 // TODO: Should we have some unified function like PrintWriter.checkError()?
550             }
551         } else {
552             System.out.print(InvokerHelper.toString(value));
553         }
554     }
555 
556     /**
557      * Print a value formatted Groovy style to the print writer.
558      *
559      * @param self  a PrintWriter
560      * @param value the value to print
561      * @since 1.0
562      */
563     public static void print(PrintWriter self, Object value) {
564         self.print(InvokerHelper.toString(value));
565     }
566 
567     /**
568      * Print a value formatted Groovy style to the print stream.
569      *
570      * @param self  a PrintStream
571      * @param value the value to print
572      * @since 1.6.0
573      */
574     public static void print(PrintStream self, Object value) {
575         self.print(InvokerHelper.toString(value));
576     }
577 
578     /**
579      * Print a value to the standard output stream.
580      * This method delegates to the owner to execute the method.
581      *
582      * @param self  a generated closure
583      * @param value the value to print
584      * @since 1.0
585      */
586     public static void print(Closure self, Object value) {
587         Object owner = getClosureOwner(self);
588         InvokerHelper.invokeMethod(owner, "print", new Object[]{value});
589     }
590 
591     /**
592      * Print a linebreak to the standard output stream.
593      *
594      * @param self any Object
595      * @since 1.0
596      */
597     public static void println(Object self) {
598         // we won't get here if we are a PrintWriter
599         if (self instanceof Writer) {
600             PrintWriter pw = new GroovyPrintWriter((Writer) self);
601             pw.println();
602         } else {
603             System.out.println();
604         }
605     }
606 
607     /**
608      * Print a linebreak to the standard output stream.
609      * This method delegates to the owner to execute the method.
610      *
611      * @param self  a closure
612      * @since 1.0
613      */
614     public static void println(Closure self) {
615         Object owner = getClosureOwner(self);
616         InvokerHelper.invokeMethod(owner, "println", EMPTY_OBJECT_ARRAY);
617     }
618 
619     private static Object getClosureOwner(Closure cls) {
620         Object owner =  cls.getOwner();
621         while (owner instanceof GeneratedClosure) {
622             owner = ((Closure) owner).getOwner();
623         }
624         return owner;
625     }
626 
627     /**
628      * Print a value formatted Groovy style (followed by a newline) to self
629      * if it is a Writer, otherwise to the standard output stream.
630      *
631      * @param self  any Object
632      * @param value the value to print
633      * @since 1.0
634      */
635     public static void println(Object self, Object value) {
636         // we won't get here if we are a PrintWriter
637         if (self instanceof Writer) {
638             final PrintWriter pw = new GroovyPrintWriter((Writer) self);
639             pw.println(value);
640         } else {
641             System.out.println(InvokerHelper.toString(value));
642         }
643     }
644 
645     /**
646      * Print a value formatted Groovy style (followed by a newline) to the print writer.
647      *
648      * @param self  a PrintWriter
649      * @param value the value to print
650      * @since 1.0
651      */
652     public static void println(PrintWriter self, Object value) {
653         self.println(InvokerHelper.toString(value));
654     }
655 
656     /**
657      * Print a value formatted Groovy style (followed by a newline) to the print stream.
658      *
659      * @param self  any Object
660      * @param value the value to print
661      * @since 1.6.0
662      */
663     public static void println(PrintStream self, Object value) {
664         self.println(InvokerHelper.toString(value));
665     }
666 
667     /**
668      * Print a value (followed by a newline) to the standard output stream.
669      * This method delegates to the owner to execute the method.
670      *
671      * @param self  a closure
672      * @param value the value to print
673      * @since 1.0
674      */
675     public static void println(Closure self, Object value) {
676         Object owner = getClosureOwner(self);
677         InvokerHelper.invokeMethod(owner, "println", new Object[]{value});
678     }
679 
680     /**
681      * Printf to a console.
682      *
683      * @param self   any Object
684      * @param format a format string
685      * @param values values referenced by the format specifiers in the format string.
686      * @since 1.0
687      */
688     public static void printf(Object self, String format, Object[] values) {
689         if (self instanceof PrintStream)
690             ((PrintStream)self).printf(format, values);
691         else
692             System.out.printf(format, values);
693     }
694 
695     /**
696      * Sprintf to a string.
697      *
698      * @param self   any Object
699      * @param format a format string
700      * @param values values referenced by the format specifiers in the format string.
701      * @return the resulting formatted string
702      * @since 1.5.0
703      */
704     public static String sprintf(Object self, String format, Object[] values) {
705         ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
706         PrintStream out = new PrintStream(outputStream);
707         out.printf(format, values);
708         return outputStream.toString();
709     }
710 
711     /**
712      * Prints a formatted string using the specified format string and
713      * arguments.
714      * <p>
715      * Examples:
716      * <pre>
717      *     printf ( "Hello, %s!\n" , [ "world" ] as String[] )
718      *     printf ( "Hello, %s!\n" , [ "Groovy" ])
719      *     printf ( "%d + %d = %d\n" , [ 1 , 2 , 1+2 ] as Integer[] )
720      *     printf ( "%d + %d = %d\n" , [ 3 , 3 , 3+3 ])
721      *
722      *     ( 1..5 ).each { printf ( "-- %d\n" , [ it ] as Integer[] ) }
723      *     ( 1..5 ).each { printf ( "-- %d\n" , [ it ] as int[] ) }
724      *     ( 0x41..0x45 ).each { printf ( "-- %c\n" , [ it ] as char[] ) }
725      *     ( 07..011 ).each { printf ( "-- %d\n" , [ it ] as byte[] ) }
726      *     ( 7..11 ).each { printf ( "-- %d\n" , [ it ] as short[] ) }
727      *     ( 7..11 ).each { printf ( "-- %d\n" , [ it ] as long[] ) }
728      *     ( 7..11 ).each { printf ( "-- %5.2f\n" , [ it ] as float[] ) }
729      *     ( 7..11 ).each { printf ( "-- %5.2g\n" , [ it ] as double[] ) }
730      * </pre>
731      *
732      * @param self   any Object
733      * @param format A format string
734      * @param arg    Argument which is referenced by the format specifiers in the format
735      *               string.  The type of <code>arg</code> should be one of Object[], List,
736      *               int[], short[], byte[], char[], boolean[], long[], float[], or double[].
737      * @since 1.0
738      */
739     public static void printf(Object self, String format, Object arg) {
740         if (self instanceof PrintStream)
741             printf((PrintStream) self, format, arg);
742         else if (self instanceof Writer)
743             printf((Writer) self, format, arg);
744         else
745             printf(System.out, format, arg);
746     }
747 
748     private static void printf(PrintStream self, String format, Object arg) {
749         self.print(sprintf(self, format, arg));
750     }
751 
752     private static void printf(Writer self, String format, Object arg) {
753         try {
754             self.write(sprintf(self, format, arg));
755         } catch (IOException e) {
756             printf(System.out, format, arg);
757         }
758     }
759 
760     /**
761      * Returns a formatted string using the specified format string and
762      * arguments.
763      *
764      * @param self   any Object
765      * @param format A format string
766      * @param arg    Argument which is referenced by the format specifiers in the format
767      *               string.  The type of <code>arg</code> should be one of Object[], List,
768      *               int[], short[], byte[], char[], boolean[], long[], float[], or double[].
769      * @return the resulting printf'd string
770      * @since 1.5.0
771      */
772     public static String sprintf(Object self, String format, Object arg) {
773         if (arg instanceof Object[]) {
774             return sprintf(self, format, (Object[]) arg);
775         }
776         if (arg instanceof List) {
777             return sprintf(self, format, ((List) arg).toArray());
778         }
779         if (!arg.getClass().isArray()) {
780             Object[] o = (Object[]) java.lang.reflect.Array.newInstance(arg.getClass(), 1);
781             o[0] = arg;
782             return sprintf(self, format, o);
783         }
784 
785         Object[] ans;
786         String elemType = arg.getClass().getName();
787         if (elemType.equals("[I")) {
788             int[] ia = (int[]) arg;
789             ans = new Integer[ia.length];
790             for (int i = 0; i < ia.length; i++) {
791                 ans[i] = ia[i];
792             }
793         } else if (elemType.equals("[C")) {
794             char[] ca = (char[]) arg;
795             ans = new Character[ca.length];
796             for (int i = 0; i < ca.length; i++) {
797                 ans[i] = ca[i];
798             }
799         } else if (elemType.equals("[Z")) {
800             boolean[] ba = (boolean[]) arg;
801             ans = new Boolean[ba.length];
802             for (int i = 0; i < ba.length; i++) {
803                 ans[i] = ba[i];
804             }
805         } else if (elemType.equals("[B")) {
806             byte[] ba = (byte[]) arg;
807             ans = new Byte[ba.length];
808             for (int i = 0; i < ba.length; i++) {
809                 ans[i] = ba[i];
810             }
811         } else if (elemType.equals("[S")) {
812             short[] sa = (short[]) arg;
813             ans = new Short[sa.length];
814             for (int i = 0; i < sa.length; i++) {
815                 ans[i] = sa[i];
816             }
817         } else if (elemType.equals("[F")) {
818             float[] fa = (float[]) arg;
819             ans = new Float[fa.length];
820             for (int i = 0; i < fa.length; i++) {
821                 ans[i] = fa[i];
822             }
823         } else if (elemType.equals("[J")) {
824             long[] la = (long[]) arg;
825             ans = new Long[la.length];
826             for (int i = 0; i < la.length; i++) {
827                 ans[i] = la[i];
828             }
829         } else if (elemType.equals("[D")) {
830             double[] da = (double[]) arg;
831             ans = new Double[da.length];
832             for (int i = 0; i < da.length; i++) {
833                 ans[i] = da[i];
834             }
835         } else {
836             throw new RuntimeException("sprintf(String," + arg + ")");
837         }
838         return sprintf(self, format, ans);
839     }
840 
841 
842     /**
843      * Inspects returns the String that matches what would be typed into a
844      * terminal to create this object.
845      *
846      * @param self any Object
847      * @return a String that matches what would be typed into a terminal to
848      *         create this object. e.g. [1, 'hello'].inspect() -> [1, "hello"]
849      * @since 1.0
850      */
851     public static String inspect(Object self) {
852         return InvokerHelper.inspect(self);
853     }
854 
855     /**
856      * Print to a console in interactive format.
857      *
858      * @param self any Object
859      * @param out  the PrintWriter used for printing
860      * @since 1.0
861      */
862     public static void print(Object self, PrintWriter out) {
863         if (out == null) {
864             out = new PrintWriter(System.out);
865         }
866         out.print(InvokerHelper.toString(self));
867     }
868 
869     /**
870      * Print to a console in interactive format.
871      *
872      * @param self any Object
873      * @param out  the PrintWriter used for printing
874      * @since 1.0
875      */
876     public static void println(Object self, PrintWriter out) {
877         if (out == null) {
878             out = new PrintWriter(System.out);
879         }
880         out.println(InvokerHelper.toString(self));
881     }
882 
883     /**
884      * Provide a dynamic method invocation method which can be overloaded in
885      * classes to implement dynamic proxies easily.
886      *
887      * @param object    any Object
888      * @param method    the name of the method to call
889      * @param arguments the arguments to use
890      * @return the result of the method call
891      * @since 1.0
892      */
893     public static Object invokeMethod(Object object, String method, Object arguments) {
894         return InvokerHelper.invokeMethod(object, method, arguments);
895     }
896 
897     // isCase methods
898     //-------------------------------------------------------------------------
899 
900     /**
901      * Method for overloading the behavior of the 'case' method in switch statements.
902      * The default implementation handles arrays types but otherwise simply delegates
903      * to Object#equals, but this may be overridden for other types. In this example:
904      * <pre> switch( a ) {
905      *   case b: //some code
906      * }</pre>
907      * "some code" is called when <code>b.isCase( a )</code> returns
908      * <code>true</code>.
909      *
910      * @param caseValue   the case value
911      * @param switchValue the switch value
912      * @return true if the switchValue is deemed to be equal to the caseValue
913      * @since 1.0
914      */
915     public static boolean isCase(Object caseValue, Object switchValue) {
916         if (caseValue.getClass().isArray()) {
917             return isCase(DefaultTypeTransformation.asCollection(caseValue), switchValue);
918         }
919         return caseValue.equals(switchValue);
920     }
921 
922     /**
923      * Special 'Case' implementation for Class, which allows testing
924      * for a certain class in a switch statement.
925      * For example:
926      * <pre>switch( obj ) {
927      *   case List :
928      *     // obj is a list
929      *     break;
930      *   case Set :
931      *     // etc
932      * }</pre>
933      *
934      * @param caseValue   the case value
935      * @param switchValue the switch value
936      * @return true if the switchValue is deemed to be assignable from the given class
937      * @since 1.0
938      */
939     public static boolean isCase(Class caseValue, Object switchValue) {
940         if (switchValue instanceof Class) {
941             Class val = (Class) switchValue;
942             return caseValue.isAssignableFrom(val);
943         }
944         return caseValue.isInstance(switchValue);
945     }
946 
947     /**
948      * 'Case' implementation for collections which tests if the 'switch'
949      * operand is contained in any of the 'case' values.
950      * For example:
951      * <pre class="groovyTestCase">switch( 3 ) {
952      *   case [1,3,5]:
953      *     assert true
954      *     break
955      *   default:
956      *     assert false
957      * }</pre>
958      *
959      * @param caseValue   the case value
960      * @param switchValue the switch value
961      * @return true if the caseValue is deemed to contain the switchValue
962      * @see java.util.Collection#contains(java.lang.Object)
963      * @since 1.0
964      */
965     public static boolean isCase(Collection caseValue, Object switchValue) {
966         return caseValue.contains(switchValue);
967     }
968 
969     /**
970      * 'Case' implementation for maps which tests the groovy truth
971      * value obtained using the 'switch' operand as key.
972      * For example:
973      * <pre class="groovyTestCase">switch( 'foo' ) {
974      *   case [foo:true, bar:false]:
975      *     assert true
976      *     break
977      *   default:
978      *     assert false
979      * }</pre>
980      *
981      * @param caseValue   the case value
982      * @param switchValue the switch value
983      * @return the groovy truth value from caseValue corresponding to the switchValue key
984      * @since 1.7.6
985      */
986     public static boolean isCase(Map caseValue, Object switchValue) {
987         return DefaultTypeTransformation.castToBoolean(caseValue.get(switchValue));
988     }
989 
990     /**
991      * Special 'case' implementation for all numbers, which delegates to the
992      * <code>compareTo()</code> method for comparing numbers of different
993      * types.
994      *
995      * @param caseValue   the case value
996      * @param switchValue the switch value
997      * @return true if the numbers are deemed equal
998      * @since 1.5.0
999      */
1000     public static boolean isCase(Number caseValue, Number switchValue) {
1001         return NumberMath.compareTo(caseValue, switchValue) == 0;
1002     }
1003 
1004     /**
1005      * Returns an iterator equivalent to this iterator with all duplicated items removed
1006      * by using the default comparator. The original iterator will become
1007      * exhausted of elements after determining the unique values. A new iterator
1008      * for the unique values will be returned.
1009      *
1010      * @param self an Iterator
1011      * @return the modified Iterator
1012      * @since 1.5.5
1013      */
1014     public static <T> Iterator<T> unique(Iterator<T> self) {
1015         return toList((Iterable<T>) unique(toList(self))).listIterator();
1016     }
1017 
1018     /**
1019      * Modifies this collection to remove all duplicated items, using the
1020      * default comparator.
1021      * <pre class="groovyTestCase">assert [1,3] == [1,3,3].unique()</pre>
1022      *
1023      * @param self a collection
1024      * @return the now modified collection
1025      * @see #unique(Collection, boolean)
1026      * @since 1.0
1027      */
1028     public static <T> Collection<T> unique(Collection<T> self) {
1029         return unique(self, true);
1030     }
1031 
1032     /**
1033      * Modifies this List to remove all duplicated items, using the
1034      * default comparator.
1035      * <pre class="groovyTestCase">assert [1,3] == [1,3,3].unique()</pre>
1036      *
1037      * @param self a List
1038      * @return the now modified List
1039      * @see #unique(Collection, boolean)
1040      * @since 2.4.0
1041      */
1042     public static <T> List<T> unique(List<T> self) {
1043         return (List<T>) unique((Collection<T>) self, true);
1044     }
1045 
1046     /**
1047      * Remove all duplicates from a given Collection using the default comparator.
1048      * If mutate is true, it works by modifying the original object (and also returning it).
1049      * If mutate is false, a new collection is returned leaving the original unchanged.
1050      * <pre class="groovyTestCase">
1051      * assert [1,3] == [1,3,3].unique()
1052      * </pre>
1053      * <pre class="groovyTestCase">
1054      * def orig = [1, 3, 2, 3]
1055      * def uniq = orig.unique(false)
1056      * assert orig == [1, 3, 2, 3]
1057      * assert uniq == [1, 3, 2]
1058      * </pre>
1059      *
1060      * @param self a collection
1061      * @param mutate false will cause a new list containing unique items from the collection to be created, true will mutate collections in place
1062      * @return the now modified collection
1063      * @since 1.8.1
1064      */
1065     public static <T> Collection<T> unique(Collection<T> self, boolean mutate) {
1066         List<T> answer = new ArrayList<T>();
1067         for (T t : self) {
1068             boolean duplicated = false;
1069             for (T t2 : answer) {
1070                 if (coercedEquals(t, t2)) {
1071                     duplicated = true;
1072                     break;
1073                 }
1074             }
1075             if (!duplicated)
1076                 answer.add(t);
1077         }
1078         if (mutate) {
1079             self.clear();
1080             self.addAll(answer);
1081         }
1082         return mutate ? self : answer ;
1083     }
1084 
1085     /**
1086      * Remove all duplicates from a given List using the default comparator.
1087      * If mutate is true, it works by modifying the original object (and also returning it).
1088      * If mutate is false, a new collection is returned leaving the original unchanged.
1089      * <pre class="groovyTestCase">
1090      * assert [1,3] == [1,3,3].unique()
1091      * </pre>
1092      * <pre class="groovyTestCase">
1093      * def orig = [1, 3, 2, 3]
1094      * def uniq = orig.unique(false)
1095      * assert orig == [1, 3, 2, 3]
1096      * assert uniq == [1, 3, 2]
1097      * </pre>
1098      *
1099      * @param self a List
1100      * @param mutate false will cause a new List containing unique items from the List to be created, true will mutate List in place
1101      * @return the now modified List
1102      * @since 2.4.0
1103      */
1104     public static <T> List<T> unique(List<T> self, boolean mutate) {
1105         return (List<T>) unique((Collection<T>) self, mutate);
1106     }
1107 
1108     /**
1109      * Provides a method that compares two comparables using Groovy's
1110      * default number aware comparator.
1111      *
1112      * @param self a Comparable
1113      * @param other another Comparable
1114      * @return a -ve number, 0 or a +ve number according to Groovy's compareTo contract
1115      * @since 1.6.0
1116      */
1117     public static int numberAwareCompareTo(Comparable self, Comparable other) {
1118         NumberAwareComparator<Comparable> numberAwareComparator = new NumberAwareComparator<Comparable>();
1119         return numberAwareComparator.compare(self, other);
1120     }
1121 
1122     /**
1123      * Returns an iterator equivalent to this iterator but with all duplicated items
1124      * removed by using a Closure to determine duplicate (equal) items.
1125      * The original iterator will be fully processed after the call.
1126      * <p>
1127      * If the closure takes a single parameter, the argument passed will be each element,
1128      * and the closure should return a value used for comparison (either using
1129      * {@link java.lang.Comparable#compareTo(java.lang.Object)} or {@link java.lang.Object#equals(java.lang.Object)}).
1130      * If the closure takes two parameters, two items from the Iterator
1131      * will be passed as arguments, and the closure should return an
1132      * int value (with 0 indicating the items are not unique).
1133      *
1134      * @param self an Iterator
1135      * @param closure a Closure used to determine unique items
1136      * @return the modified Iterator
1137      * @since 1.5.5
1138      */
1139     public static <T> Iterator<T> unique(Iterator<T> self, @ClosureParams(value=FromString.class, options={"T","T,T"}) Closure closure) {
1140         return toList((Iterable<T>) unique(toList(self), closure)).listIterator();
1141     }
1142 
1143     /**
1144      * A convenience method for making a collection unique using a Closure
1145      * to determine duplicate (equal) items.
1146      * <p>
1147      * If the closure takes a single parameter, the
1148      * argument passed will be each element, and the closure
1149      * should return a value used for comparison (either using
1150      * {@link java.lang.Comparable#compareTo(java.lang.Object)} or {@link java.lang.Object#equals(java.lang.Object)}).
1151      * If the closure takes two parameters, two items from the collection
1152      * will be passed as arguments, and the closure should return an
1153      * int value (with 0 indicating the items are not unique).
1154      * <pre class="groovyTestCase">assert [1,4] == [1,3,4,5].unique { it % 2 }</pre>
1155      * <pre class="groovyTestCase">assert [2,3,4] == [2,3,3,4].unique { a, b -> a <=> b }</pre>
1156      *
1157      * @param self    a Collection
1158      * @param closure a 1 or 2 arg Closure used to determine unique items
1159      * @return self   without any duplicates
1160      * @see #unique(Collection, boolean, Closure)
1161      * @since 1.0
1162      */
1163     public static <T> Collection<T> unique(Collection<T> self, @ClosureParams(value=FromString.class, options={"T","T,T"}) Closure closure) {
1164         return unique(self, true, closure);
1165     }
1166 
1167     /**
1168      * A convenience method for making a List unique using a Closure
1169      * to determine duplicate (equal) items.
1170      * <p>
1171      * If the closure takes a single parameter, the
1172      * argument passed will be each element, and the closure
1173      * should return a value used for comparison (either using
1174      * {@link java.lang.Comparable#compareTo(java.lang.Object)} or {@link java.lang.Object#equals(java.lang.Object)}).
1175      * If the closure takes two parameters, two items from the List
1176      * will be passed as arguments, and the closure should return an
1177      * int value (with 0 indicating the items are not unique).
1178      * <pre class="groovyTestCase">assert [1,4] == [1,3,4,5].unique { it % 2 }</pre>
1179      * <pre class="groovyTestCase">assert [2,3,4] == [2,3,3,4].unique { a, b -> a <=> b }</pre>
1180      *
1181      * @param self    a List
1182      * @param closure a 1 or 2 arg Closure used to determine unique items
1183      * @return self   without any duplicates
1184      * @see #unique(Collection, boolean, Closure)
1185      * @since 2.4.0
1186      */
1187     public static <T> List<T> unique(List<T> self, @ClosureParams(value=FromString.class, options={"T","T,T"}) Closure closure) {
1188         return (List<T>) unique((Collection<T>) self, true, closure);
1189     }
1190 
1191     /**
1192      * A convenience method for making a collection unique using a Closure to determine duplicate (equal) items.
1193      * If mutate is true, it works on the receiver object and returns it. If mutate is false, a new collection is returned.
1194      * <p>
1195      * If the closure takes a single parameter, each element from the Collection will be passed to the closure. The closure
1196      * should return a value used for comparison (either using {@link java.lang.Comparable#compareTo(java.lang.Object)} or
1197      * {@link java.lang.Object#equals(java.lang.Object)}). If the closure takes two parameters, two items from the collection
1198      * will be passed as arguments, and the closure should return an int value (with 0 indicating the items are not unique).
1199      * <pre class="groovyTestCase">
1200      * def orig = [1, 3, 4, 5]
1201      * def uniq = orig.unique(false) { it % 2 }
1202      * assert orig == [1, 3, 4, 5]
1203      * assert uniq == [1, 4]
1204      * </pre>
1205      * <pre class="groovyTestCase">
1206      * def orig = [2, 3, 3, 4]
1207      * def uniq = orig.unique(false) { a, b -> a <=> b }
1208      * assert orig == [2, 3, 3, 4]
1209      * assert uniq == [2, 3, 4]
1210      * </pre>
1211      *
1212      * @param self    a Collection
1213      * @param mutate  false will always cause a new list to be created, true will mutate lists in place
1214      * @param closure a 1 or 2 arg Closure used to determine unique items
1215      * @return self   without any duplicates
1216      * @since 1.8.1
1217      */
1218     public static <T> Collection<T> unique(Collection<T> self, boolean mutate, @ClosureParams(value=FromString.class, options={"T","T,T"}) Closure closure) {
1219         // use a comparator of one item or two
1220         int params = closure.getMaximumNumberOfParameters();
1221         if (params == 1) {
1222             self = unique(self, mutate, new OrderBy<T>(closure, true));
1223         } else {
1224             self = unique(self, mutate, new ClosureComparator<T>(closure));
1225         }
1226         return self;
1227     }
1228 
1229     /**
1230      * A convenience method for making a List unique using a Closure to determine duplicate (equal) items.
1231      * If mutate is true, it works on the receiver object and returns it. If mutate is false, a new collection is returned.
1232      * <p>
1233      * If the closure takes a single parameter, each element from the List will be passed to the closure. The closure
1234      * should return a value used for comparison (either using {@link java.lang.Comparable#compareTo(java.lang.Object)} or
1235      * {@link java.lang.Object#equals(java.lang.Object)}). If the closure takes two parameters, two items from the collection
1236      * will be passed as arguments, and the closure should return an int value (with 0 indicating the items are not unique).
1237      * <pre class="groovyTestCase">
1238      * def orig = [1, 3, 4, 5]
1239      * def uniq = orig.unique(false) { it % 2 }
1240      * assert orig == [1, 3, 4, 5]
1241      * assert uniq == [1, 4]
1242      * </pre>
1243      * <pre class="groovyTestCase">
1244      * def orig = [2, 3, 3, 4]
1245      * def uniq = orig.unique(false) { a, b -> a <=> b }
1246      * assert orig == [2, 3, 3, 4]
1247      * assert uniq == [2, 3, 4]
1248      * </pre>
1249      *
1250      * @param self    a List
1251      * @param mutate  false will always cause a new list to be created, true will mutate lists in place
1252      * @param closure a 1 or 2 arg Closure used to determine unique items
1253      * @return self   without any duplicates
1254      * @since 2.4.0
1255      */
1256     public static <T> List<T> unique(List<T> self, boolean mutate, @ClosureParams(value=FromString.class, options={"T","T,T"}) Closure closure) {
1257         return (List<T>) unique((Collection<T>) self, mutate, closure);
1258     }
1259 
1260     /**
1261      * Returns an iterator equivalent to this iterator with all duplicated
1262      * items removed by using the supplied comparator.
1263      *
1264      * @param self an Iterator
1265      * @param comparator a Comparator
1266      * @return the modified Iterator
1267      * @since 1.5.5
1268      */
1269     public static <T> Iterator<T> unique(Iterator<T> self, Comparator<T> comparator) {
1270         return toList((Iterable<T>) unique(toList(self), comparator)).listIterator();
1271     }
1272 
1273     /**
1274      * Remove all duplicates from a given Collection.
1275      * Works on the original object (and also returns it).
1276      * The order of members in the Collection are compared by the given Comparator.
1277      * For each duplicate, the first member which is returned
1278      * by the given Collection's iterator is retained, but all other ones are removed.
1279      * The given Collection's original order is preserved.
1280      * <p>
1281      * <pre class="groovyTestCase">
1282      * class Person {
1283      *     def fname, lname
1284      *     String toString() {
1285      *         return fname + " " + lname
1286      *     }
1287      * }
1288      *
1289      * class PersonComparator implements Comparator {
1290      *     int compare(Object o1, Object o2) {
1291      *         Person p1 = (Person) o1
1292      *         Person p2 = (Person) o2
1293      *         if (p1.lname != p2.lname)
1294      *             return p1.lname.compareTo(p2.lname)
1295      *         else
1296      *             return p1.fname.compareTo(p2.fname)
1297      *     }
1298      *
1299      *     boolean equals(Object obj) {
1300      *         return this.equals(obj)
1301      *     }
1302      * }
1303      *
1304      * Person a = new Person(fname:"John", lname:"Taylor")
1305      * Person b = new Person(fname:"Clark", lname:"Taylor")
1306      * Person c = new Person(fname:"Tom", lname:"Cruz")
1307      * Person d = new Person(fname:"Clark", lname:"Taylor")
1308      *
1309      * def list = [a, b, c, d]
1310      * List list2 = list.unique(new PersonComparator())
1311      * assert( list2 == list && list == [a, b, c] )
1312      * </pre>
1313      *
1314      * @param self       a Collection
1315      * @param comparator a Comparator
1316      * @return self      the now modified collection without duplicates
1317      * @see #unique(java.util.Collection, boolean, java.util.Comparator)
1318      * @since 1.0
1319      */
1320     public static <T> Collection<T> unique(Collection<T> self, Comparator<T> comparator) {
1321         return unique(self, true, comparator) ;
1322     }
1323 
1324     /**
1325      * Remove all duplicates from a given List.
1326      * Works on the original object (and also returns it).
1327      * The order of members in the List are compared by the given Comparator.
1328      * For each duplicate, the first member which is returned
1329      * by the given List's iterator is retained, but all other ones are removed.
1330      * The given List's original order is preserved.
1331      * <p>
1332      * <pre class="groovyTestCase">
1333      * class Person {
1334      *     def fname, lname
1335      *     String toString() {
1336      *         return fname + " " + lname
1337      *     }
1338      * }
1339      *
1340      * class PersonComparator implements Comparator {
1341      *     int compare(Object o1, Object o2) {
1342      *         Person p1 = (Person) o1
1343      *         Person p2 = (Person) o2
1344      *         if (p1.lname != p2.lname)
1345      *             return p1.lname.compareTo(p2.lname)
1346      *         else
1347      *             return p1.fname.compareTo(p2.fname)
1348      *     }
1349      *
1350      *     boolean equals(Object obj) {
1351      *         return this.equals(obj)
1352      *     }
1353      * }
1354      *
1355      * Person a = new Person(fname:"John", lname:"Taylor")
1356      * Person b = new Person(fname:"Clark", lname:"Taylor")
1357      * Person c = new Person(fname:"Tom", lname:"Cruz")
1358      * Person d = new Person(fname:"Clark", lname:"Taylor")
1359      *
1360      * def list = [a, b, c, d]
1361      * List list2 = list.unique(new PersonComparator())
1362      * assert( list2 == list && list == [a, b, c] )
1363      * </pre>
1364      *
1365      * @param self       a List
1366      * @param comparator a Comparator
1367      * @return self      the now modified List without duplicates
1368      * @see #unique(java.util.Collection, boolean, java.util.Comparator)
1369      * @since 2.4.0
1370      */
1371     public static <T> List<T> unique(List<T> self, Comparator<T> comparator) {
1372         return (List<T>) unique((Collection<T>) self, true, comparator);
1373     }
1374 
1375     /**
1376      * Remove all duplicates from a given Collection.
1377      * If mutate is true, it works on the original object (and also returns it). If mutate is false, a new collection is returned.
1378      * The order of members in the Collection are compared by the given Comparator.
1379      * For each duplicate, the first member which is returned
1380      * by the given Collection's iterator is retained, but all other ones are removed.
1381      * The given Collection's original order is preserved.
1382      * <p>
1383      * <pre class="groovyTestCase">
1384      * class Person {
1385      *     def fname, lname
1386      *     String toString() {
1387      *         return fname + " " + lname
1388      *     }
1389      * }
1390      *
1391      * class PersonComparator implements Comparator {
1392      *     int compare(Object o1, Object o2) {
1393      *         Person p1 = (Person) o1
1394      *         Person p2 = (Person) o2
1395      *         if (p1.lname != p2.lname)
1396      *             return p1.lname.compareTo(p2.lname)
1397      *         else
1398      *             return p1.fname.compareTo(p2.fname)
1399      *     }
1400      *
1401      *     boolean equals(Object obj) {
1402      *         return this.equals(obj)
1403      *     }
1404      * }
1405      *
1406      * Person a = new Person(fname:"John", lname:"Taylor")
1407      * Person b = new Person(fname:"Clark", lname:"Taylor")
1408      * Person c = new Person(fname:"Tom", lname:"Cruz")
1409      * Person d = new Person(fname:"Clark", lname:"Taylor")
1410      *
1411      * def list = [a, b, c, d]
1412      * List list2 = list.unique(false, new PersonComparator())
1413      * assert( list2 != list && list2 == [a, b, c] )
1414      * </pre>
1415      *
1416      * @param self       a Collection
1417      * @param mutate     false will always cause a new collection to be created, true will mutate collections in place
1418      * @param comparator a Comparator
1419      * @return self      the collection without duplicates
1420      * @since 1.8.1
1421      */
1422     public static <T> Collection<T> unique(Collection<T> self, boolean mutate, Comparator<T> comparator) {
1423         List<T> answer = new ArrayList<T>();
1424         for (T t : self) {
1425             boolean duplicated = false;
1426             for (T t2 : answer) {
1427                 if (comparator.compare(t, t2) == 0) {
1428                     duplicated = true;
1429                     break;
1430                 }
1431             }
1432             if (!duplicated)
1433                 answer.add(t);
1434         }
1435         if (mutate) {
1436             self.clear();
1437             self.addAll(answer);
1438         }
1439         return mutate ? self : answer;
1440     }
1441 
1442     /**
1443      * Remove all duplicates from a given List.
1444      * If mutate is true, it works on the original object (and also returns it). If mutate is false, a new List is returned.
1445      * The order of members in the List are compared by the given Comparator.
1446      * For each duplicate, the first member which is returned
1447      * by the given List's iterator is retained, but all other ones are removed.
1448      * The given List's original order is preserved.
1449      * <p>
1450      * <pre class="groovyTestCase">
1451      * class Person {
1452      *     def fname, lname
1453      *     String toString() {
1454      *         return fname + " " + lname
1455      *     }
1456      * }
1457      *
1458      * class PersonComparator implements Comparator {
1459      *     int compare(Object o1, Object o2) {
1460      *         Person p1 = (Person) o1
1461      *         Person p2 = (Person) o2
1462      *         if (p1.lname != p2.lname)
1463      *             return p1.lname.compareTo(p2.lname)
1464      *         else
1465      *             return p1.fname.compareTo(p2.fname)
1466      *     }
1467      *
1468      *     boolean equals(Object obj) {
1469      *         return this.equals(obj)
1470      *     }
1471      * }
1472      *
1473      * Person a = new Person(fname:"John", lname:"Taylor")
1474      * Person b = new Person(fname:"Clark", lname:"Taylor")
1475      * Person c = new Person(fname:"Tom", lname:"Cruz")
1476      * Person d = new Person(fname:"Clark", lname:"Taylor")
1477      *
1478      * def list = [a, b, c, d]
1479      * List list2 = list.unique(false, new PersonComparator())
1480      * assert( list2 != list && list2 == [a, b, c] )
1481      * </pre>
1482      *
1483      * @param self       a List
1484      * @param mutate     false will always cause a new List to be created, true will mutate List in place
1485      * @param comparator a Comparator
1486      * @return self      the List without duplicates
1487      * @since 2.4.0
1488      */
1489     public static <T> List<T> unique(List<T> self, boolean mutate, Comparator<T> comparator) {
1490         return (List<T>) unique((Collection<T>) self, mutate, comparator);
1491     }
1492 
1493     /**
1494      * Returns an iterator equivalent to this iterator but with all duplicated items
1495      * removed where duplicate (equal) items are deduced by calling the supplied Closure condition.
1496      * <p>
1497      * If the supplied Closure takes a single parameter, the argument passed will be each element,
1498      * and the closure should return a value used for comparison (either using
1499      * {@link java.lang.Comparable#compareTo(java.lang.Object)} or {@link java.lang.Object#equals(java.lang.Object)}).
1500      * If the closure takes two parameters, two items from the Iterator
1501      * will be passed as arguments, and the closure should return an
1502      * int value (with 0 indicating the items are not unique).
1503      * <pre class="groovyTestCase">
1504      * def items = "Hello".toList() + [null, null] + "there".toList()
1505      * def toLower = { it == null ? null : it.toLowerCase() }
1506      * def noDups = items.iterator().toUnique(toLower).toList()
1507      * assert noDups == ['H', 'e', 'l', 'o', null, 't', 'r']
1508      * </pre>
1509      * <pre class="groovyTestCase">assert [1,4] == [1,3,4,5].toUnique { it % 2 }</pre>
1510      * <pre class="groovyTestCase">assert [2,3,4] == [2,3,3,4].toUnique { a, b -> a <=> b }</pre>
1511      *
1512      * @param self an Iterator
1513      * @param condition a Closure used to determine unique items
1514      * @return an Iterator with no duplicate items
1515      * @since 2.4.0
1516      */
1517     public static <T> Iterator<T> toUnique(Iterator<T> self, @ClosureParams(value=FromString.class, options={"T","T,T"}) Closure condition) {
1518         return new UniqueIterator<T>(self, condition.getMaximumNumberOfParameters() == 1
1519                 ? new OrderBy<T>(condition, true)
1520                 : new ClosureComparator<T>(condition));
1521     }
1522 
1523     private static final class UniqueIterator<E> implements Iterator<E> {
1524         private final Iterator<E> delegate;
1525         private final Set<E> seen;
1526         private boolean exhausted;
1527         private E next;
1528 
1529         private UniqueIterator(Iterator<E> delegate, Comparator<E> comparator) {
1530             this.delegate = delegate;
1531             seen = new TreeSet<E>(comparator);
1532             advance();
1533         }
1534 
1535         public boolean hasNext() {
1536             return !exhausted;
1537         }
1538 
1539         public E next() {
1540             if (exhausted) throw new NoSuchElementException();
1541             E result = next;
1542             advance();
1543             return result;
1544         }
1545 
1546         public void remove() {
1547             if (exhausted) throw new NoSuchElementException();
1548             delegate.remove();
1549         }
1550 
1551         private void advance() {
1552             boolean foundNext = false;
1553             while (!foundNext && !exhausted) {
1554                 exhausted = !delegate.hasNext();
1555                 if (!exhausted) {
1556                     next = delegate.next();
1557                     foundNext = seen.add(next);
1558                 }
1559             }
1560         }
1561     }
1562 
1563     /**
1564      * Returns an iterator equivalent to this iterator with all duplicated
1565      * items removed by using the supplied comparator.
1566      *
1567      * @param self an Iterator
1568      * @param comparator a Comparator used to determine unique (equal) items
1569      *        If {@code null}, the Comparable natural ordering of the elements will be used.
1570      * @return an Iterator with no duplicate items
1571      * @since 2.4.0
1572      */
1573     public static <T> Iterator<T> toUnique(Iterator<T> self, Comparator<T> comparator) {
1574         return new UniqueIterator<T>(self, comparator);
1575     }
1576 
1577     /**
1578      * Returns an iterator equivalent to this iterator with all duplicated
1579      * items removed by using the natural ordering of the items.
1580      *
1581      * @param self an Iterator
1582      * @return an Iterator with no duplicate items
1583      * @since 2.4.0
1584      */
1585     public static <T> Iterator<T> toUnique(Iterator<T> self) {
1586         return new UniqueIterator<T>(self, null);
1587     }
1588 
1589     /**
1590      * Returns a Collection containing the items from the Iterable but with duplicates removed.
1591      * The items in the Iterable are compared by the given Comparator.
1592      * For each duplicate, the first member which is returned from the
1593      * Iterable is retained, but all other ones are removed.
1594      * <p>
1595      * <pre class="groovyTestCase">
1596      * class Person {
1597      *     def fname, lname
1598      *     String toString() {
1599      *         return fname + " " + lname
1600      *     }
1601      * }
1602      *
1603      * class PersonComparator implements Comparator {
1604      *     int compare(Object o1, Object o2) {
1605      *         Person p1 = (Person) o1
1606      *         Person p2 = (Person) o2
1607      *         if (p1.lname != p2.lname)
1608      *             return p1.lname.compareTo(p2.lname)
1609      *         else
1610      *             return p1.fname.compareTo(p2.fname)
1611      *     }
1612      *
1613      *     boolean equals(Object obj) {
1614      *         return this.equals(obj)
1615      *     }
1616      * }
1617      *
1618      * Person a = new Person(fname:"John", lname:"Taylor")
1619      * Person b = new Person(fname:"Clark", lname:"Taylor")
1620      * Person c = new Person(fname:"Tom", lname:"Cruz")
1621      * Person d = new Person(fname:"Clark", lname:"Taylor")
1622      *
1623      * def list = [a, b, c, d]
1624      * List list2 = list.toUnique(new PersonComparator())
1625      * assert( list2 == list && list == [a, b, c] )
1626      * </pre>
1627      *
1628      * @param self       an Iterable
1629      * @param comparator a Comparator used to determine unique (equal) items
1630      *        If {@code null}, the Comparable natural ordering of the elements will be used.
1631      * @return the Collection of non-duplicate items
1632      * @since 2.4.0
1633      */
1634     public static <T> Collection<T> toUnique(Iterable<T> self, Comparator<T> comparator) {
1635         Collection<T> result = createSimilarCollection((Collection<T>) self);
1636         addAll(result, toUnique(self.iterator(), comparator));
1637         return result;
1638     }
1639 
1640     /**
1641      * Returns a List containing the items from the List but with duplicates removed.
1642      * The items in the List are compared by the given Comparator.
1643      * For each duplicate, the first member which is returned from the
1644      * List is retained, but all other ones are removed.
1645      * <p>
1646      * <pre class="groovyTestCase">
1647      * class Person {
1648      *     def fname, lname
1649      *     String toString() {
1650      *         return fname + " " + lname
1651      *     }
1652      * }
1653      *
1654      * class PersonComparator implements Comparator {
1655      *     int compare(Object o1, Object o2) {
1656      *         Person p1 = (Person) o1
1657      *         Person p2 = (Person) o2
1658      *         if (p1.lname != p2.lname)
1659      *             return p1.lname.compareTo(p2.lname)
1660      *         else
1661      *             return p1.fname.compareTo(p2.fname)
1662      *     }
1663      *
1664      *     boolean equals(Object obj) {
1665      *         return this.equals(obj)
1666      *     }
1667      * }
1668      *
1669      * Person a = new Person(fname:"John", lname:"Taylor")
1670      * Person b = new Person(fname:"Clark", lname:"Taylor")
1671      * Person c = new Person(fname:"Tom", lname:"Cruz")
1672      * Person d = new Person(fname:"Clark", lname:"Taylor")
1673      *
1674      * def list = [a, b, c, d]
1675      * List list2 = list.toUnique(new PersonComparator())
1676      * assert( list2 == list && list == [a, b, c] )
1677      * </pre>
1678      *
1679      * @param self       a List
1680      * @param comparator a Comparator used to determine unique (equal) items
1681      *        If {@code null}, the Comparable natural ordering of the elements will be used.
1682      * @return the List of non-duplicate items
1683      * @since 2.4.0
1684      */
1685     public static <T> List<T> toUnique(List<T> self, Comparator<T> comparator) {
1686         return (List<T>) toUnique((Iterable<T>) self, comparator);
1687     }
1688 
1689     /**
1690      * Returns a Collection containing the items from the Iterable but with duplicates removed
1691      * using the natural ordering of the items to determine uniqueness.
1692      * <p>
1693      * <pre class="groovyTestCase">
1694      * String[] letters = ['c', 'a', 't', 's', 'a', 't', 'h', 'a', 't']
1695      * String[] expected = ['c', 'a', 't', 's', 'h']
1696      * assert letters.toUnique() == expected
1697      * </pre>
1698      *
1699      * @param self       an Iterable
1700      * @return the Collection of non-duplicate items
1701      * @since 2.4.0
1702      */
1703     public static <T> Collection<T> toUnique(Iterable<T> self) {
1704         return toUnique(self, (Comparator<T>) null);
1705     }
1706 
1707     /**
1708      * Returns a List containing the items from the List but with duplicates removed
1709      * using the natural ordering of the items to determine uniqueness.
1710      * <p>
1711      * <pre class="groovyTestCase">
1712      * def letters = ['c', 'a', 't', 's', 'a', 't', 'h', 'a', 't']
1713      * def expected = ['c', 'a', 't', 's', 'h']
1714      * assert letters.toUnique() == expected
1715      * </pre>
1716      *
1717      * @param self       a List
1718      * @return the List of non-duplicate items
1719      * @since 2.4.0
1720      */
1721     public static <T> List<T> toUnique(List<T> self) {
1722         return toUnique(self, (Comparator<T>) null);
1723     }
1724 
1725     /**
1726      * Returns a Collection containing the items from the Iterable but with duplicates removed.
1727      * The items in the Iterable are compared by the given Closure condition.
1728      * For each duplicate, the first member which is returned from the
1729      * Iterable is retained, but all other ones are removed.
1730      * <p>
1731      * If the closure takes a single parameter, each element from the Iterable will be passed to the closure. The closure
1732      * should return a value used for comparison (either using {@link java.lang.Comparable#compareTo(java.lang.Object)} or
1733      * {@link java.lang.Object#equals(java.lang.Object)}). If the closure takes two parameters, two items from the Iterable
1734      * will be passed as arguments, and the closure should return an int value (with 0 indicating the items are not unique).
1735      * <p>
1736      * <pre class="groovyTestCase">
1737      * class Person {
1738      *     def fname, lname
1739      *     String toString() {
1740      *         return fname + " " + lname
1741      *     }
1742      * }
1743      *
1744      * Person a = new Person(fname:"John", lname:"Taylor")
1745      * Person b = new Person(fname:"Clark", lname:"Taylor")
1746      * Person c = new Person(fname:"Tom", lname:"Cruz")
1747      * Person d = new Person(fname:"Clark", lname:"Taylor")
1748      *
1749      * def list = [a, b, c, d]
1750      * def list2 = list.toUnique{ p1, p2 -> p1.lname != p2.lname ? p1.lname &lt;=&gt; p2.lname : p1.fname &lt;=&gt; p2.fname }
1751      * assert( list2 == [a, b, c] && list == [a, b, c, d] )
1752      * def list3 = list.toUnique{ it.toString() }
1753      * assert( list3 == [a, b, c] && list == [a, b, c, d] )
1754      * </pre>
1755      *
1756      * @param self      an Iterable
1757      * @param condition a Closure used to determine unique items
1758      * @return a new Collection
1759      * @see #toUnique(Iterable, Comparator)
1760      * @since 2.4.0
1761      */
1762     public static <T> Collection<T> toUnique(Iterable<T> self, @ClosureParams(value = FromString.class, options = {"T", "T,T"}) Closure condition) {
1763         Comparator<T> comparator = condition.getMaximumNumberOfParameters() == 1
1764                 ? new OrderBy<T>(condition, true)
1765                 : new ClosureComparator<T>(condition);
1766         return toUnique(self, comparator);
1767     }
1768 
1769     /**
1770      * Returns a List containing the items from the List but with duplicates removed.
1771      * The items in the List are compared by the given Closure condition.
1772      * For each duplicate, the first member which is returned from the
1773      * Iterable is retained, but all other ones are removed.
1774      * <p>
1775      * If the closure takes a single parameter, each element from the Iterable will be passed to the closure. The closure
1776      * should return a value used for comparison (either using {@link java.lang.Comparable#compareTo(java.lang.Object)} or
1777      * {@link java.lang.Object#equals(java.lang.Object)}). If the closure takes two parameters, two items from the Iterable
1778      * will be passed as arguments, and the closure should return an int value (with 0 indicating the items are not unique).
1779      * <p>
1780      * <pre class="groovyTestCase">
1781      * class Person {
1782      *     def fname, lname
1783      *     String toString() {
1784      *         return fname + " " + lname
1785      *     }
1786      * }
1787      *
1788      * Person a = new Person(fname:"John", lname:"Taylor")
1789      * Person b = new Person(fname:"Clark", lname:"Taylor")
1790      * Person c = new Person(fname:"Tom", lname:"Cruz")
1791      * Person d = new Person(fname:"Clark", lname:"Taylor")
1792      *
1793      * def list = [a, b, c, d]
1794      * def list2 = list.toUnique{ p1, p2 -> p1.lname != p2.lname ? p1.lname &lt;=&gt; p2.lname : p1.fname &lt;=&gt; p2.fname }
1795      * assert( list2 == [a, b, c] && list == [a, b, c, d] )
1796      * def list3 = list.toUnique{ it.toString() }
1797      * assert( list3 == [a, b, c] && list == [a, b, c, d] )
1798      * </pre>
1799      *
1800      * @param self      a List
1801      * @param condition a Closure used to determine unique items
1802      * @return a new List
1803      * @see #toUnique(Iterable, Comparator)
1804      * @since 2.4.0
1805      */
1806     public static <T> List<T> toUnique(List<T> self, @ClosureParams(value = FromString.class, options = {"T", "T,T"}) Closure condition) {
1807         return (List<T>) toUnique((Iterable<T>) self, condition);
1808     }
1809 
1810     /**
1811      * Returns a new Array containing the items from the original Array but with duplicates removed with the supplied
1812      * comparator determining which items are unique.
1813      * <p>
1814      * <pre class="groovyTestCase">
1815      * String[] letters = ['c', 'a', 't', 's', 'A', 't', 'h', 'a', 'T']
1816      * String[] lower = ['c', 'a', 't', 's', 'h']
1817      * class LowerComparator implements Comparator {
1818      *     int compare(let1, let2) { let1.toLowerCase() <=> let2.toLowerCase() }
1819      * }
1820      * assert letters.toUnique(new LowerComparator()) == lower
1821      * </pre>
1822      *
1823      * @param self an array
1824      * @param comparator a Comparator used to determine unique (equal) items
1825      *        If {@code null}, the Comparable natural ordering of the elements will be used.
1826      * @return the unique items from the array
1827      */
1828     @SuppressWarnings("unchecked")
1829     public static <T> T[] toUnique(T[] self, Comparator<T> comparator) {
1830         Collection<T> items = toUnique(toList(self), comparator);
1831         T[] result = createSimilarArray(self, items.size());
1832         return items.toArray(result);
1833     }
1834 
1835     /**
1836      * Returns a new Array containing the items from the original Array but with duplicates removed using the
1837      * natural ordering of the items in the array.
1838      * <p>
1839      * <pre class="groovyTestCase">
1840      * String[] letters = ['c', 'a', 't', 's', 'a', 't', 'h', 'a', 't']
1841      * String[] expected = ['c', 'a', 't', 's', 'h']
1842      * def result = letters.toUnique()
1843      * assert result == expected
1844      * assert result.class.componentType == String
1845      * </pre>
1846      *
1847      * @param self an array
1848      * @return the unique items from the array
1849      */
1850     @SuppressWarnings("unchecked")
1851     public static <T> T[] toUnique(T[] self) {
1852         return (T[]) toUnique(self, (Comparator) null);
1853     }
1854 
1855     /**
1856      * Returns a new Array containing the items from the original Array but with duplicates removed with the supplied
1857      * comparator determining which items are unique.
1858      * <p>
1859      * <pre class="groovyTestCase">
1860      * String[] letters = ['c', 'a', 't', 's', 'A', 't', 'h', 'a', 'T']
1861      * String[] expected = ['c', 'a', 't', 's', 'h']
1862      * assert letters.toUnique{ p1, p2 -> p1.toLowerCase() <=> p2.toLowerCase() } == expected
1863      * assert letters.toUnique{ it.toLowerCase() } == expected
1864      * </pre>
1865      *
1866      * @param self an array
1867      * @param condition a Closure used to determine unique items
1868      * @return the unique items from the array
1869      */
1870     @SuppressWarnings("unchecked")
1871     public static <T> T[] toUnique(T[] self, @ClosureParams(value=FromString.class, options={"T","T,T"}) Closure condition) {
1872         Comparator<T> comparator = condition.getMaximumNumberOfParameters() == 1
1873                 ? new OrderBy<T>(condition, true)
1874                 : new ClosureComparator<T>(condition);
1875         return toUnique(self, comparator);
1876     }
1877 
1878     /**
1879      * Iterates through an aggregate type or data structure,
1880      * passing each item to the given closure.  Custom types may utilize this
1881      * method by simply providing an "iterator()" method.  The items returned
1882      * from the resulting iterator will be passed to the closure.
1883      *
1884      * @param self    the object over which we iterate
1885      * @param closure the closure applied on each element found
1886      * @return the self Object
1887      * @since 1.0
1888      */
1889     public static <T> T each(T self, Closure closure) {
1890         each(InvokerHelper.asIterator(self), closure);
1891         return self;
1892     }
1893 
1894     /**
1895      * Iterates through an aggregate type or data structure,
1896      * passing each item and the item's index (a counter starting at
1897      * zero) to the given closure.
1898      *
1899      * @param self    an Object
1900      * @param closure a Closure to operate on each item
1901      * @return the self Object
1902      * @since 1.0
1903      */
1904     public static <T> T eachWithIndex(T self, Closure closure) {
1905         final Object[] args = new Object[2];
1906         int counter = 0;
1907         for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext();) {
1908             args[0] = iter.next();
1909             args[1] = counter++;
1910             closure.call(args);
1911         }
1912         return self;
1913     }
1914 
1915     /**
1916      * Iterates through an iterable type,
1917      * passing each item and the item's index (a counter starting at
1918      * zero) to the given closure.
1919      *
1920      * @param self    an Iterable
1921      * @param closure a Closure to operate on each item
1922      * @return the self Iterable
1923      * @since 2.3.0
1924      */
1925     public static <T> Iterable<T> eachWithIndex(Iterable<T> self, @ClosureParams(value=FromString.class, options="T,Integer") Closure closure) {
1926         eachWithIndex(self.iterator(), closure);
1927         return self;
1928     }
1929 
1930     /**
1931      * Iterates through an iterator type,
1932      * passing each item and the item's index (a counter starting at
1933      * zero) to the given closure.
1934      *
1935      * @param self    an Iterable
1936      * @param closure a Closure to operate on each item
1937      * @return the self Iterable
1938      * @since 2.3.0
1939      */
1940     public static <T> Iterator<T> eachWithIndex(Iterator<T> self, @ClosureParams(value=FromString.class, options="T,Integer") Closure closure) {
1941         final Object[] args = new Object[2];
1942         int counter = 0;
1943         while (self.hasNext()) {
1944             args[0] = self.next();
1945             args[1] = counter++;
1946             closure.call(args);
1947         }
1948         return self;
1949     }
1950 
1951     /**
1952      * Iterates through an Collection,
1953      * passing each item and the item's index (a counter starting at
1954      * zero) to the given closure.
1955      *
1956      * @param self    an Collection
1957      * @param closure a Closure to operate on each item
1958      * @return the self Collection
1959      * @since 2.4.0
1960      */
1961     public static <T> Collection<T> eachWithIndex(Collection<T> self, @ClosureParams(value=FromString.class, options="T,Integer") Closure closure) {
1962         return (Collection<T>) eachWithIndex((Iterable<T>) self, closure);
1963     }
1964 
1965     /**
1966      * Iterates through a List,
1967      * passing each item and the item's index (a counter starting at
1968      * zero) to the given closure.
1969      *
1970      * @param self    a List
1971      * @param closure a Closure to operate on each item
1972      * @return the self List
1973      * @since 2.4.0
1974      */
1975     public static <T> List<T> eachWithIndex(List<T> self, @ClosureParams(value=FromString.class, options="T,Integer") Closure closure) {
1976         return (List<T>) eachWithIndex((Iterable<T>) self, closure);
1977     }
1978 
1979     /**
1980      * Iterates through an Set,
1981      * passing each item and the item's index (a counter starting at
1982      * zero) to the given closure.
1983      *
1984      * @param self    an Set
1985      * @param closure a Closure to operate on each item
1986      * @return the self Set
1987      * @since 2.4.0
1988      */
1989     public static <T> Set<T> eachWithIndex(Set<T> self, @ClosureParams(value=FromString.class, options="T,Integer") Closure closure) {
1990         return (Set<T>) eachWithIndex((Iterable<T>) self, closure);
1991     }
1992 
1993     /**
1994      * Iterates through an SortedSet,
1995      * passing each item and the item's index (a counter starting at
1996      * zero) to the given closure.
1997      *
1998      * @param self    an SortedSet
1999      * @param closure a Closure to operate on each item
2000      * @return the self SortedSet
2001      * @since 2.4.0
2002      */
2003     public static <T> SortedSet<T> eachWithIndex(SortedSet<T> self, @ClosureParams(value=FromString.class, options="T,Integer") Closure closure) {
2004         return (SortedSet<T>) eachWithIndex((Iterable<T>) self, closure);
2005     }
2006 
2007     /**
2008      * Iterates through an Iterable, passing each item to the given closure.
2009      *
2010      * @param self    the Iterable over which we iterate
2011      * @param closure the closure applied on each element found
2012      * @return the self Iterable
2013      */
2014     public static <T> Iterable<T> each(Iterable<T> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure closure) {
2015         each(self.iterator(), closure);
2016         return self;
2017     }
2018 
2019     /**
2020      * Iterates through an Iterator, passing each item to the given closure.
2021      *
2022      * @param self    the Iterator over which we iterate
2023      * @param closure the closure applied on each element found
2024      * @return the self Iterator
2025      * @since 2.4.0
2026      */
2027     public static <T> Iterator<T> each(Iterator<T> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure closure) {
2028         while (self.hasNext()) {
2029             Object arg = self.next();
2030             closure.call(arg);
2031         }
2032         return self;
2033     }
2034 
2035     /**
2036      * Iterates through an Collection, passing each item to the given closure.
2037      *
2038      * @param self    the Collection over which we iterate
2039      * @param closure the closure applied on each element found
2040      * @return the self Collection
2041      * @since 2.4.0
2042      */
2043     public static <T> Collection<T> each(Collection<T> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure closure) {
2044         return (Collection<T>) each((Iterable<T>) self, closure);
2045     }
2046 
2047     /**
2048      * Iterates through a List, passing each item to the given closure.
2049      *
2050      * @param self    the List over which we iterate
2051      * @param closure the closure applied on each element found
2052      * @return the self List
2053      * @since 2.4.0
2054      */
2055     public static <T> List<T> each(List<T> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure closure) {
2056         return (List<T>) each((Iterable<T>) self, closure);
2057     }
2058 
2059     /**
2060      * Iterates through an Set, passing each item to the given closure.
2061      *
2062      * @param self    the Set over which we iterate
2063      * @param closure the closure applied on each element found
2064      * @return the self Set
2065      * @since 2.4.0
2066      */
2067     public static <T> Set<T> each(Set<T> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure closure) {
2068         return (Set<T>) each((Iterable<T>) self, closure);
2069     }
2070 
2071     /**
2072      * Iterates through an SortedSet, passing each item to the given closure.
2073      *
2074      * @param self    the SortedSet over which we iterate
2075      * @param closure the closure applied on each element found
2076      * @return the self SortedSet
2077      * @since 2.4.0
2078      */
2079     public static <T> SortedSet<T> each(SortedSet<T> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure closure) {
2080         return (SortedSet<T>) each((Iterable<T>) self, closure);
2081     }
2082 
2083     /**
2084      * Allows a Map to be iterated through using a closure. If the
2085      * closure takes one parameter then it will be passed the Map.Entry
2086      * otherwise if the closure takes two parameters then it will be
2087      * passed the key and the value.
2088      * <pre class="groovyTestCase">def result = ""
2089      * [a:1, b:3].each { key, value -> result += "$key$value" }
2090      * assert result == "a1b3"</pre>
2091      * <pre class="groovyTestCase">def result = ""
2092      * [a:1, b:3].each { entry -> result += entry }
2093      * assert result == "a=1b=3"</pre>
2094      *
2095      * In general, the order in which the map contents are processed
2096      * cannot be guaranteed. In practise, specialized forms of Map,
2097      * e.g. a TreeMap will have its contents processed according to
2098      * the natural ordering of the map.
2099      *
2100      * @param self    the map over which we iterate
2101      * @param closure the 1 or 2 arg closure applied on each entry of the map
2102      * @return returns the self parameter
2103      * @since 1.5.0
2104      */
2105     public static <K, V> Map<K, V> each(Map<K, V> self, @ClosureParams(MapEntryOrKeyValue.class) Closure closure) {
2106         for (Map.Entry entry : self.entrySet()) {
2107             callClosureForMapEntry(closure, entry);
2108         }
2109         return self;
2110     }
2111 
2112     /**
2113      * Allows a Map to be iterated through in reverse order using a closure.
2114      *
2115      * In general, the order in which the map contents are processed
2116      * cannot be guaranteed. In practise, specialized forms of Map,
2117      * e.g. a TreeMap will have its contents processed according to the
2118      * reverse of the natural ordering of the map.
2119      *
2120      * @param self    the map over which we iterate
2121      * @param closure the 1 or 2 arg closure applied on each entry of the map
2122      * @return returns the self parameter
2123      * @see #each(Map, Closure)
2124      * @since 1.7.2
2125      */
2126     public static <K, V> Map<K, V> reverseEach(Map<K, V> self, @ClosureParams(MapEntryOrKeyValue.class) Closure closure) {
2127         final Iterator<Map.Entry<K, V>> entries = reverse(self.entrySet().iterator());
2128         while (entries.hasNext()) {
2129             callClosureForMapEntry(closure, entries.next());
2130         }
2131         return self;
2132     }
2133 
2134     /**
2135      * Allows a Map to be iterated through using a closure. If the
2136      * closure takes two parameters then it will be passed the Map.Entry and
2137      * the item's index (a counter starting at zero) otherwise if the closure
2138      * takes three parameters then it will be passed the key, the value, and
2139      * the index.
2140      * <pre class="groovyTestCase">def result = ""
2141      * [a:1, b:3].eachWithIndex { key, value, index -> result += "$index($key$value)" }
2142      * assert result == "0(a1)1(b3)"</pre>
2143      * <pre class="groovyTestCase">def result = ""
2144      * [a:1, b:3].eachWithIndex { entry, index -> result += "$index($entry)" }
2145      * assert result == "0(a=1)1(b=3)"</pre>
2146      *
2147      * @param self    the map over which we iterate
2148      * @param closure a 2 or 3 arg Closure to operate on each item
2149      * @return the self Object
2150      * @since 1.5.0
2151      */
2152     public static <K, V> Map<K, V> eachWithIndex(Map<K, V> self, @ClosureParams(value=MapEntryOrKeyValue.class, options="index=true") Closure closure) {
2153         int counter = 0;
2154         for (Map.Entry entry : self.entrySet()) {
2155             callClosureForMapEntryAndCounter(closure, entry, counter++);
2156         }
2157         return self;
2158     }
2159 
2160     /**
2161      * Iterate over each element of the list in the reverse order.
2162      * <pre class="groovyTestCase">def result = []
2163      * [1,2,3].reverseEach { result &lt;&lt; it }
2164      * assert result == [3,2,1]</pre>
2165      *
2166      * @param self    a List
2167      * @param closure a closure to which each item is passed.
2168      * @return the original list
2169      * @since 1.5.0
2170      */
2171     public static <T> List<T> reverseEach(List<T> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure closure) {
2172         each(new ReverseListIterator<T>(self), closure);
2173         return self;
2174     }
2175 
2176     /**
2177      * Iterate over each element of the array in the reverse order.
2178      *
2179      * @param self    an array
2180      * @param closure a closure to which each item is passed
2181      * @return the original array
2182      * @since 1.5.2
2183      */
2184     public static <T> T[] reverseEach(T[] self, @ClosureParams(FirstParam.Component.class) Closure closure) {
2185         each(new ReverseListIterator<T>(Arrays.asList(self)), closure);
2186         return self;
2187     }
2188 
2189     /**
2190      * Used to determine if the given predicate closure is valid (i.e.&nsbp;returns
2191      * <code>true</code> for all items in this data structure).
2192      * A simple example for a list:
2193      * <pre>def list = [3,4,5]
2194      * def greaterThanTwo = list.every { it > 2 }
2195      * </pre>
2196      *
2197      * @param self    the object over which we iterate
2198      * @param closure the closure predicate used for matching
2199      * @return true if every iteration of the object matches the closure predicate
2200      * @since 1.0
2201      */
2202     public static boolean every(Object self, Closure closure) {
2203         BooleanClosureWrapper bcw = new BooleanClosureWrapper(closure);
2204         for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext();) {
2205             if (!bcw.call(iter.next())) {
2206                 return false;
2207             }
2208         }
2209         return true;
2210     }
2211 
2212     /**
2213      * Used to determine if the given predicate closure is valid (i.e.&nsbp;returns
2214      * <code>true</code> for all items in this iterator).
2215      * A simple example for a list:
2216      * <pre>def list = [3,4,5]
2217      * def greaterThanTwo = list.iterator().every { it > 2 }
2218      * </pre>
2219      *
2220      * @param self    the iterator over which we iterate
2221      * @param closure the closure predicate used for matching
2222      * @return true if every iteration of the object matches the closure predicate
2223      * @since 2.3.0
2224      */
2225     public static <T> boolean every(Iterator<T> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure closure) {
2226         BooleanClosureWrapper bcw = new BooleanClosureWrapper(closure);
2227         while (self.hasNext()) {
2228             if (!bcw.call(self.next())) {
2229                 return false;
2230             }
2231         }
2232         return true;
2233     }
2234 
2235     /**
2236      * Used to determine if the given predicate closure is valid (i.e.&nsbp;returns
2237      * <code>true</code> for all items in this iterable).
2238      * A simple example for a list:
2239      * <pre>def list = [3,4,5]
2240      * def greaterThanTwo = list.every { it > 2 }
2241      * </pre>
2242      *
2243      * @param self    the iterable over which we iterate
2244      * @param closure the closure predicate used for matching
2245      * @return true if every iteration of the object matches the closure predicate
2246      * @since 2.3.0
2247      */
2248     public static <T> boolean every(Iterable<T> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure closure) {
2249         return every(self.iterator(), closure);
2250     }
2251 
2252     /**
2253      * Iterates over the entries of a map, and checks whether a predicate is
2254      * valid for all entries. If the
2255      * closure takes one parameter then it will be passed the Map.Entry
2256      * otherwise if the closure takes two parameters then it will be
2257      * passed the key and the value.
2258      * <pre class="groovyTestCase">def map = [a:1, b:2.0, c:2L]
2259      * assert !map.every { key, value -> value instanceof Integer }
2260      * assert map.every { entry -> entry.value instanceof Number }</pre>
2261      *
2262      * @param self    the map over which we iterate
2263      * @param closure the 1 or 2 arg Closure predicate used for matching
2264      * @return true if every entry of the map matches the closure predicate
2265      * @since 1.5.0
2266      */
2267     public static <K, V> boolean every(Map<K, V> self, @ClosureParams(value=MapEntryOrKeyValue.class) Closure closure) {
2268         BooleanClosureWrapper bcw = new BooleanClosureWrapper(closure);
2269         for (Map.Entry<K, V> entry : self.entrySet()) {
2270             if (!bcw.callForMap(entry)) {
2271                 return false;
2272             }
2273         }
2274         return true;
2275     }
2276 
2277     /**
2278      * Iterates over every element of a collection, and checks whether all
2279      * elements are <code>true</code> according to the Groovy Truth.
2280      * Equivalent to <code>self.every({element -> element})</code>
2281      *
2282      * @param self the object over which we iterate
2283      * @return true if every item in the collection matches the closure
2284      *         predicate
2285      * @since 1.5.0
2286      */
2287     public static boolean every(Object self) {
2288         BooleanReturningMethodInvoker bmi = new BooleanReturningMethodInvoker();
2289         for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext();) {
2290             if (!bmi.convertToBoolean(iter.next())) {
2291                 return false;
2292             }
2293         }
2294         return true;
2295     }
2296 
2297     /**
2298      * Iterates over the contents of an object or collection, and checks whether a
2299      * predicate is valid for at least one element.
2300      *
2301      * @param self    the object over which we iterate
2302      * @param closure the closure predicate used for matching
2303      * @return true   if any iteration for the object matches the closure predicate
2304      * @since 1.0
2305      */
2306     public static boolean any(Object self, Closure closure) {
2307         BooleanClosureWrapper bcw = new BooleanClosureWrapper(closure);
2308         for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext();) {
2309             if (bcw.call(iter.next())) return true;
2310         }
2311         return false;
2312     }
2313 
2314     /**
2315      * Iterates over the contents of an iterator, and checks whether a
2316      * predicate is valid for at least one element.
2317      *
2318      * @param self    the iterator over which we iterate
2319      * @param closure the closure predicate used for matching
2320      * @return true   if any iteration for the object matches the closure predicate
2321      * @since 1.0
2322      */
2323     public static <T> boolean any(Iterator<T> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure closure) {
2324         BooleanClosureWrapper bcw = new BooleanClosureWrapper(closure);
2325         for (Iterator iter = self; iter.hasNext();) {
2326             if (bcw.call(iter.next())) return true;
2327         }
2328         return false;
2329     }
2330 
2331     /**
2332      * Iterates over the contents of an iterable, and checks whether a
2333      * predicate is valid for at least one element.
2334      *
2335      * @param self    the iterable over which we iterate
2336      * @param closure the closure predicate used for matching
2337      * @return true   if any iteration for the object matches the closure predicate
2338      * @since 1.0
2339      */
2340     public static <T> boolean any(Iterable<T> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure closure) {
2341         BooleanClosureWrapper bcw = new BooleanClosureWrapper(closure);
2342         for (Iterator<T> iter = self.iterator(); iter.hasNext();) {
2343             if (bcw.call(iter.next())) return true;
2344         }
2345         return false;
2346     }
2347 
2348     /**
2349      * Iterates over the entries of a map, and checks whether a predicate is
2350      * valid for at least one entry. If the
2351      * closure takes one parameter then it will be passed the Map.Entry
2352      * otherwise if the closure takes two parameters then it will be
2353      * passed the key and the value.
2354      * <pre class="groovyTestCase">
2355      * assert [2:3, 4:5, 5:10].any { key, value -> key * 2 == value }
2356      * assert ![2:3, 4:5, 5:10].any { entry -> entry.key == entry.value * 2 }
2357      * </pre>
2358      *
2359      * @param self    the map over which we iterate
2360      * @param closure the 1 or 2 arg closure predicate used for matching
2361      * @return true if any entry in the map matches the closure predicate
2362      * @since 1.5.0
2363      */
2364     public static <K, V> boolean any(Map<K, V> self, @ClosureParams(MapEntryOrKeyValue.class) Closure<?> closure) {
2365         BooleanClosureWrapper bcw = new BooleanClosureWrapper(closure);
2366         for (Map.Entry<K, V> entry : self.entrySet()) {
2367             if (bcw.callForMap(entry)) {
2368                 return true;
2369             }
2370         }
2371         return false;
2372     }
2373 
2374     /**
2375      * Iterates over the elements of a collection, and checks whether at least
2376      * one element is true according to the Groovy Truth.
2377      * Equivalent to self.any({element -> element})
2378      *
2379      * @param self the object over which we iterate
2380      * @return true if any item in the collection matches the closure predicate
2381      * @since 1.5.0
2382      */
2383     public static boolean any(Object self) {
2384         BooleanReturningMethodInvoker bmi = new BooleanReturningMethodInvoker();
2385         for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext();) {
2386             if (bmi.convertToBoolean(iter.next())) {
2387                 return true;
2388             }
2389         }
2390         return false;
2391     }
2392 
2393     /**
2394      * Iterates over the collection of items which this Object represents and returns each item that matches
2395      * the given filter - calling the <code>{@link #isCase(java.lang.Object, java.lang.Object)}</code>
2396      * method used by switch statements.  This method can be used with different
2397      * kinds of filters like regular expressions, classes, ranges etc.
2398      * Example:
2399      * <pre class="groovyTestCase">
2400      * def list = ['a', 'b', 'aa', 'bc', 3, 4.5]
2401      * assert list.grep( ~/a+/ )  == ['a', 'aa']
2402      * assert list.grep( ~/../ )  == ['aa', 'bc']
2403      * assert list.grep( Number ) == [ 3, 4.5 ]
2404      * assert list.grep{ it.toString().size() == 1 } == [ 'a', 'b', 3 ]
2405      * </pre>
2406      *
2407      * @param self   the object over which we iterate
2408      * @param filter the filter to perform on the object (using the {@link #isCase(java.lang.Object, java.lang.Object)} method)
2409      * @return a collection of objects which match the filter
2410      * @since 1.5.6
2411      */
2412     public static Collection grep(Object self, Object filter) {
2413         Collection answer = createSimilarOrDefaultCollection(self);
2414         BooleanReturningMethodInvoker bmi = new BooleanReturningMethodInvoker("isCase");
2415         for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext();) {
2416             Object object = iter.next();
2417             if (bmi.invoke(filter, object)) {
2418                 answer.add(object);
2419             }
2420         }
2421         return answer;
2422     }
2423 
2424     /**
2425      * Iterates over the collection of items and returns each item that matches
2426      * the given filter - calling the <code>{@link #isCase(java.lang.Object, java.lang.Object)}</code>
2427      * method used by switch statements.  This method can be used with different
2428      * kinds of filters like regular expressions, classes, ranges etc.
2429      * Example:
2430      * <pre class="groovyTestCase">
2431      * def list = ['a', 'b', 'aa', 'bc', 3, 4.5]
2432      * assert list.grep( ~/a+/ )  == ['a', 'aa']
2433      * assert list.grep( ~/../ )  == ['aa', 'bc']
2434      * assert list.grep( Number ) == [ 3, 4.5 ]
2435      * assert list.grep{ it.toString().size() == 1 } == [ 'a', 'b', 3 ]
2436      * </pre>
2437      *
2438      * @param self   a collection
2439      * @param filter the filter to perform on each element of the collection (using the {@link #isCase(java.lang.Object, java.lang.Object)} method)
2440      * @return a collection of objects which match the filter
2441      * @since 2.0
2442      */
2443     public static <T> Collection<T> grep(Collection<T> self, Object filter) {
2444         Collection<T> answer = createSimilarCollection(self);
2445         BooleanReturningMethodInvoker bmi = new BooleanReturningMethodInvoker("isCase");
2446         for (T element : self) {
2447             if (bmi.invoke(filter, element)) {
2448                 answer.add(element);
2449             }
2450         }
2451         return answer;
2452     }
2453 
2454     /**
2455      * Iterates over the collection of items and returns each item that matches
2456      * the given filter - calling the <code>{@link #isCase(java.lang.Object, java.lang.Object)}</code>
2457      * method used by switch statements.  This method can be used with different
2458      * kinds of filters like regular expressions, classes, ranges etc.
2459      * Example:
2460      * <pre class="groovyTestCase">
2461      * def list = ['a', 'b', 'aa', 'bc', 3, 4.5]
2462      * assert list.grep( ~/a+/ )  == ['a', 'aa']
2463      * assert list.grep( ~/../ )  == ['aa', 'bc']
2464      * assert list.grep( Number ) == [ 3, 4.5 ]
2465      * assert list.grep{ it.toString().size() == 1 } == [ 'a', 'b', 3 ]
2466      * </pre>
2467      *
2468      * @param self   a List
2469      * @param filter the filter to perform on each element of the collection (using the {@link #isCase(java.lang.Object, java.lang.Object)} method)
2470      * @return a List of objects which match the filter
2471      * @since 2.4.0
2472      */
2473     public static <T> List<T> grep(List<T> self, Object filter) {
2474         return (List<T>) grep((Collection<T>) self, filter);
2475     }
2476 
2477     /**
2478      * Iterates over the collection of items and returns each item that matches
2479      * the given filter - calling the <code>{@link #isCase(java.lang.Object, java.lang.Object)}</code>
2480      * method used by switch statements.  This method can be used with different
2481      * kinds of filters like regular expressions, classes, ranges etc.
2482      * Example:
2483      * <pre class="groovyTestCase">
2484      * def set = ['a', 'b', 'aa', 'bc', 3, 4.5] as Set
2485      * assert set.grep( ~/a+/ )  == ['a', 'aa'] as Set
2486      * assert set.grep( ~/../ )  == ['aa', 'bc'] as Set
2487      * assert set.grep( Number ) == [ 3, 4.5 ] as Set
2488      * assert set.grep{ it.toString().size() == 1 } == [ 'a', 'b', 3 ] as Set
2489      * </pre>
2490      *
2491      * @param self   a Set
2492      * @param filter the filter to perform on each element of the collection (using the {@link #isCase(java.lang.Object, java.lang.Object)} method)
2493      * @return a Set of objects which match the filter
2494      * @since 2.4.0
2495      */
2496     public static <T> Set<T> grep(Set<T> self, Object filter) {
2497         return (Set<T>) grep((Collection<T>) self, filter);
2498     }
2499 
2500     /**
2501      * Iterates over the array of items and returns a collection of items that match
2502      * the given filter - calling the <code>{@link #isCase(java.lang.Object, java.lang.Object)}</code>
2503      * method used by switch statements. This method can be used with different
2504      * kinds of filters like regular expressions, classes, ranges etc.
2505      * Example:
2506      * <pre class="groovyTestCase">
2507      * def items = ['a', 'b', 'aa', 'bc', 3, 4.5] as Object[]
2508      * assert items.grep( ~/a+/ )  == ['a', 'aa']
2509      * assert items.grep( ~/../ )  == ['aa', 'bc']
2510      * assert items.grep( Number ) == [ 3, 4.5 ]
2511      * assert items.grep{ it.toString().size() == 1 } == [ 'a', 'b', 3 ]
2512      * </pre>
2513      *
2514      * @param self   an array
2515      * @param filter the filter to perform on each element of the array (using the {@link #isCase(java.lang.Object, java.lang.Object)} method)
2516      * @return a collection of objects which match the filter
2517      * @since 2.0
2518      */
2519     public static <T> Collection<T> grep(T[] self, Object filter) {
2520         Collection<T> answer = new ArrayList<T>();
2521         BooleanReturningMethodInvoker bmi = new BooleanReturningMethodInvoker("isCase");
2522         for (T element : self) {
2523             if (bmi.invoke(filter, element)) {
2524                 answer.add(element);
2525             }
2526         }
2527         return answer;
2528     }
2529 
2530     /**
2531      * Iterates over the collection of items which this Object represents and returns each item that matches
2532      * using the IDENTITY Closure as a filter - effectively returning all elements which satisfy Groovy truth.
2533      * <p>
2534      * Example:
2535      * <pre class="groovyTestCase">
2536      * def items = [1, 2, 0, false, true, '', 'foo', [], [4, 5], null]
2537      * assert items.grep() == [1, 2, true, 'foo', [4, 5]]
2538      * </pre>
2539      *
2540      * @param self   the object over which we iterate
2541      * @return a collection of objects which match the filter
2542      * @since 1.8.1
2543      * @see Closure#IDENTITY
2544      */
2545     public static Collection grep(Object self) {
2546         return grep(self, Closure.IDENTITY);
2547     }
2548 
2549     /**
2550      * Iterates over the collection returning each element that matches
2551      * using the IDENTITY Closure as a filter - effectively returning all elements which satisfy Groovy truth.
2552      * <p>
2553      * Example:
2554      * <pre class="groovyTestCase">
2555      * def items = [1, 2, 0, false, true, '', 'foo', [], [4, 5], null]
2556      * assert items.grep() == [1, 2, true, 'foo', [4, 5]]
2557      * </pre>
2558      *
2559      * @param self a Collection
2560      * @return a collection of elements satisfy Groovy truth
2561      * @see Closure#IDENTITY
2562      * @since 2.0
2563      */
2564     public static <T> Collection<T> grep(Collection<T> self) {
2565         return grep(self, Closure.IDENTITY);
2566     }
2567 
2568     /**
2569      * Iterates over the collection returning each element that matches
2570      * using the IDENTITY Closure as a filter - effectively returning all elements which satisfy Groovy truth.
2571      * <p>
2572      * Example:
2573      * <pre class="groovyTestCase">
2574      * def items = [1, 2, 0, false, true, '', 'foo', [], [4, 5], null]
2575      * assert items.grep() == [1, 2, true, 'foo', [4, 5]]
2576      * </pre>
2577      *
2578      * @param self a List
2579      * @return a List of elements satisfy Groovy truth
2580      * @see Closure#IDENTITY
2581      * @since 2.4.0
2582      */
2583     public static <T> List<T> grep(List<T> self) {
2584         return grep(self, Closure.IDENTITY);
2585     }
2586 
2587     /**
2588      * Iterates over the collection returning each element that matches
2589      * using the IDENTITY Closure as a filter - effectively returning all elements which satisfy Groovy truth.
2590      * <p>
2591      * Example:
2592      * <pre class="groovyTestCase">
2593      * def items = [1, 2, 0, false, true, '', 'foo', [], [4, 5], null] as Set
2594      * assert items.grep() == [1, 2, true, 'foo', [4, 5]] as Set
2595      * </pre>
2596      *
2597      * @param self a Set
2598      * @return a Set of elements satisfy Groovy truth
2599      * @see Closure#IDENTITY
2600      * @since 2.4.0
2601      */
2602     public static <T> Set<T> grep(Set<T> self) {
2603         return grep(self, Closure.IDENTITY);
2604     }
2605 
2606     /**
2607      * Iterates over the array returning each element that matches
2608      * using the IDENTITY Closure as a filter - effectively returning all elements which satisfy Groovy truth.
2609      * <p>
2610      * Example:
2611      * <pre class="groovyTestCase">
2612      * def items = [1, 2, 0, false, true, '', 'foo', [], [4, 5], null] as Object[]
2613      * assert items.grep() == [1, 2, true, 'foo', [4, 5]]
2614      * </pre>
2615      *
2616      * @param self an array
2617      * @return a collection of elements which satisfy Groovy truth
2618      * @see Closure#IDENTITY
2619      * @since 2.0
2620      */
2621     @SuppressWarnings("unchecked")
2622     public static <T> Collection<T> grep(T[] self) {
2623         return grep(self, Closure.IDENTITY);
2624     }
2625 
2626     /**
2627      * Counts the number of occurrences of the given value from the
2628      * items within this Iterator.
2629      * Comparison is done using Groovy's == operator (using
2630      * <code>compareTo(value) == 0</code> or <code>equals(value)</code> ).
2631      * The iterator will become exhausted of elements after determining the count value.
2632      *
2633      * @param self  the Iterator from which we count the number of matching occurrences
2634      * @param value the value being searched for
2635      * @return the number of occurrences
2636      * @since 1.5.0
2637      */
2638     public static Number count(Iterator self, Object value) {
2639         long answer = 0;
2640         while (self.hasNext()) {
2641             if (DefaultTypeTransformation.compareEqual(self.next(), value)) {
2642                 ++answer;
2643             }
2644         }
2645         // for b/c with Java return an int if we can
2646         if (answer <= Integer.MAX_VALUE) return (int) answer;
2647         return answer;
2648     }
2649 
2650     /**
2651      * Counts the number of occurrences which satisfy the given closure from the
2652      * items within this Iterator.
2653      * The iterator will become exhausted of elements after determining the count value.
2654      * <p>
2655      * Example usage:
2656      * <pre class="groovyTestCase">assert [2,4,2,1,3,5,2,4,3].toSet().iterator().count{ it % 2 == 0 } == 2</pre>
2657      *
2658      * @param self  the Iterator from which we count the number of matching occurrences
2659      * @param closure a closure condition
2660      * @return the number of occurrences
2661      * @since 1.8.0
2662      */
2663     public static <T> Number count(Iterator<T> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure closure) {
2664         long answer = 0;
2665         BooleanClosureWrapper bcw = new BooleanClosureWrapper(closure);
2666         while (self.hasNext()) {
2667             if (bcw.call(self.next())) {
2668                 ++answer;
2669             }
2670         }
2671         // for b/c with Java return an int if we can
2672         if (answer <= Integer.MAX_VALUE) return (int) answer;
2673         return answer;
2674     }
2675 
2676     /**
2677      * @deprecated use count(Iterable, Closure)
2678      * @since 1.0
2679      */
2680     @Deprecated
2681     public static Number count(Collection self, Object value) {
2682         return count(self.iterator(), value);
2683     }
2684 
2685     /**
2686      * Counts the number of occurrences of the given value inside this Iterable.
2687      * Comparison is done using Groovy's == operator (using
2688      * <code>compareTo(value) == 0</code> or <code>equals(value)</code> ).
2689      * <p>
2690      * Example usage:
2691      * <pre class="groovyTestCase">assert [2,4,2,1,3,5,2,4,3].count(4) == 2</pre>
2692      *
2693      * @param self  the Iterable within which we count the number of occurrences
2694      * @param value the value being searched for
2695      * @return the number of occurrences
2696      * @since 2.2.0
2697      */
2698     public static Number count(Iterable self, Object value) {
2699         return count(self.iterator(), value);
2700     }
2701 
2702     /**
2703      * @deprecated use count(Iterable, Closure)
2704      * @since 1.8.0
2705      */
2706     @Deprecated
2707     public static Number count(Collection self, Closure closure) {
2708         return count(self.iterator(), closure);
2709     }
2710 
2711     /**
2712      * Counts the number of occurrences which satisfy the given closure from inside this Iterable.
2713      * <p>
2714      * Example usage:
2715      * <pre class="groovyTestCase">assert [2,4,2,1,3,5,2,4,3].count{ it % 2 == 0 } == 5</pre>
2716      *
2717      * @param self  the Iterable within which we count the number of occurrences
2718      * @param closure a closure condition
2719      * @return the number of occurrences
2720      * @since 2.2.0
2721      */
2722     public static <T> Number count(Iterable<T> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure closure) {
2723         return count(self.iterator(), closure);
2724     }
2725 
2726     /**
2727      * Counts the number of occurrences which satisfy the given closure from inside this map.
2728      * If the closure takes one parameter then it will be passed the Map.Entry.
2729      * Otherwise, the closure should take two parameters and will be passed the key and value.
2730      * <p>
2731      * Example usage:
2732      * <pre class="groovyTestCase">assert [a:1, b:1, c:2, d:2].count{ k,v -> k == 'a' || v == 2 } == 3</pre>
2733      *
2734      * @param self  the map within which we count the number of occurrences
2735      * @param closure a 1 or 2 arg Closure condition applying on the entries
2736      * @return the number of occurrences
2737      * @since 1.8.0
2738      */
2739     public static <K,V> Number count(Map<K,V> self, @ClosureParams(MapEntryOrKeyValue.class) Closure<?> closure) {
2740         long answer = 0;
2741         BooleanClosureWrapper bcw = new BooleanClosureWrapper(closure);
2742         for (Object entry : self.entrySet()) {
2743             if (bcw.callForMap((Map.Entry)entry)) {
2744                 ++answer;
2745             }
2746         }
2747         // for b/c with Java return an int if we can
2748         if (answer <= Integer.MAX_VALUE) return (int) answer;
2749         return answer;
2750     }
2751 
2752     /**
2753      * Counts the number of occurrences of the given value inside this array.
2754      * Comparison is done using Groovy's == operator (using
2755      * <code>compareTo(value) == 0</code> or <code>equals(value)</code> ).
2756      *
2757      * @param self  the array within which we count the number of occurrences
2758      * @param value the value being searched for
2759      * @return the number of occurrences
2760      * @since 1.6.4
2761      */
2762     public static Number count(Object[] self, Object value) {
2763         return count((Iterable)Arrays.asList(self), value);
2764     }
2765 
2766     /**
2767      * Counts the number of occurrences which satisfy the given closure from inside this array.
2768      *
2769      * @param self  the array within which we count the number of occurrences
2770      * @param closure a closure condition
2771      * @return the number of occurrences
2772      * @since 1.8.0
2773      */
2774     public static <T> Number count(T[] self, @ClosureParams(FirstParam.Component.class) Closure closure) {
2775         return count((Iterable)Arrays.asList(self), closure);
2776     }
2777 
2778     /**
2779      * Counts the number of occurrences of the given value inside this array.
2780      * Comparison is done using Groovy's == operator (using
2781      * <code>compareTo(value) == 0</code> or <code>equals(value)</code> ).
2782      *
2783      * @param self  the array within which we count the number of occurrences
2784      * @param value the value being searched for
2785      * @return the number of occurrences
2786      * @since 1.6.4
2787      */
2788     public static Number count(int[] self, Object value) {
2789         return count(InvokerHelper.asIterator(self), value);
2790     }
2791 
2792     /**
2793      * Counts the number of occurrences of the given value inside this array.
2794      * Comparison is done using Groovy's == operator (using
2795      * <code>compareTo(value) == 0</code> or <code>equals(value)</code> ).
2796      *
2797      * @param self  the array within which we count the number of occurrences
2798      * @param value the value being searched for
2799      * @return the number of occurrences
2800      * @since 1.6.4
2801      */
2802     public static Number count(long[] self, Object value) {
2803         return count(InvokerHelper.asIterator(self), value);
2804     }
2805 
2806     /**
2807      * Counts the number of occurrences of the given value inside this array.
2808      * Comparison is done using Groovy's == operator (using
2809      * <code>compareTo(value) == 0</code> or <code>equals(value)</code> ).
2810      *
2811      * @param self  the array within which we count the number of occurrences
2812      * @param value the value being searched for
2813      * @return the number of occurrences
2814      * @since 1.6.4
2815      */
2816     public static Number count(short[] self, Object value) {
2817         return count(InvokerHelper.asIterator(self), value);
2818     }
2819 
2820     /**
2821      * Counts the number of occurrences of the given value inside this array.
2822      * Comparison is done using Groovy's == operator (using
2823      * <code>compareTo(value) == 0</code> or <code>equals(value)</code> ).
2824      *
2825      * @param self  the array within which we count the number of occurrences
2826      * @param value the value being searched for
2827      * @return the number of occurrences
2828      * @since 1.6.4
2829      */
2830     public static Number count(char[] self, Object value) {
2831         return count(InvokerHelper.asIterator(self), value);
2832     }
2833 
2834     /**
2835      * Counts the number of occurrences of the given value inside this array.
2836      * Comparison is done using Groovy's == operator (using
2837      * <code>compareTo(value) == 0</code> or <code>equals(value)</code> ).
2838      *
2839      * @param self  the array within which we count the number of occurrences
2840      * @param value the value being searched for
2841      * @return the number of occurrences
2842      * @since 1.6.4
2843      */
2844     public static Number count(boolean[] self, Object value) {
2845         return count(InvokerHelper.asIterator(self), value);
2846     }
2847 
2848     /**
2849      * Counts the number of occurrences of the given value inside this array.
2850      * Comparison is done using Groovy's == operator (using
2851      * <code>compareTo(value) == 0</code> or <code>equals(value)</code> ).
2852      *
2853      * @param self  the array within which we count the number of occurrences
2854      * @param value the value being searched for
2855      * @return the number of occurrences
2856      * @since 1.6.4
2857      */
2858     public static Number count(double[] self, Object value) {
2859         return count(InvokerHelper.asIterator(self), value);
2860     }
2861 
2862     /**
2863      * Counts the number of occurrences of the given value inside this array.
2864      * Comparison is done using Groovy's == operator (using
2865      * <code>compareTo(value) == 0</code> or <code>equals(value)</code> ).
2866      *
2867      * @param self  the array within which we count the number of occurrences
2868      * @param value the value being searched for
2869      * @return the number of occurrences
2870      * @since 1.6.4
2871      */
2872     public static Number count(float[] self, Object value) {
2873         return count(InvokerHelper.asIterator(self), value);
2874     }
2875 
2876     /**
2877      * Counts the number of occurrences of the given value inside this array.
2878      * Comparison is done using Groovy's == operator (using
2879      * <code>compareTo(value) == 0</code> or <code>equals(value)</code> ).
2880      *
2881      * @param self  the array within which we count the number of occurrences
2882      * @param value the value being searched for
2883      * @return the number of occurrences
2884      * @since 1.6.4
2885      */
2886     public static Number count(byte[] self, Object value) {
2887         return count(InvokerHelper.asIterator(self), value);
2888     }
2889 
2890     /**
2891      * @deprecated Use the Iterable version of toList instead
2892      * @see #toList(Iterable)
2893      * @since 1.0
2894      */
2895     @Deprecated
2896     public static <T> List<T> toList(Collection<T> self) {
2897         List<T> answer = new ArrayList<T>(self.size());
2898         answer.addAll(self);
2899         return answer;
2900     }
2901 
2902     /**
2903      * Convert an iterator to a List. The iterator will become
2904      * exhausted of elements after making this conversion.
2905      *
2906      * @param self an iterator
2907      * @return a List
2908      * @since 1.5.0
2909      */
2910     public static <T> List<T> toList(Iterator<T> self) {
2911         List<T> answer = new ArrayList<T>();
2912         while (self.hasNext()) {
2913             answer.add(self.next());
2914         }
2915         return answer;
2916     }
2917 
2918     /**
2919      * Convert an Iterable to a List. The Iterable's iterator will
2920      * become exhausted of elements after making this conversion.
2921      * <p>
2922      * Example usage:
2923      * <pre class="groovyTestCase">def x = [1,2,3] as HashSet
2924      * assert x.class == HashSet
2925      * assert x.toList() instanceof List</pre>
2926      *
2927      * @param self an Iterable
2928      * @return a List
2929      * @since 1.8.7
2930      */
2931     public static <T> List<T> toList(Iterable<T> self) {
2932         return toList(self.iterator());
2933     }
2934 
2935     /**
2936      * Convert an enumeration to a List.
2937      *
2938      * @param self an enumeration
2939      * @return a List
2940      * @since 1.5.0
2941      */
2942     public static <T> List<T> toList(Enumeration<T> self) {
2943         List<T> answer = new ArrayList<T>();
2944         while (self.hasMoreElements()) {
2945             answer.add(self.nextElement());
2946         }
2947         return answer;
2948     }
2949 
2950     /**
2951      * Collates this iterable into sub-lists of length <code>size</code>.
2952      * Example:
2953      * <pre class="groovyTestCase">def list = [ 1, 2, 3, 4, 5, 6, 7 ]
2954      * def coll = list.collate( 3 )
2955      * assert coll == [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7 ] ]</pre>
2956      *
2957      * @param self          an Iterable
2958      * @param size          the length of each sub-list in the returned list
2959      * @return a List containing the data collated into sub-lists
2960      * @since 2.4.0
2961      */
2962     public static <T> List<List<T>> collate(Iterable<T> self, int size) {
2963         return collate(self, size, true);
2964     }
2965 
2966     /**
2967      * @deprecated use the Iterable variant instead
2968      * @see #collate(Iterable, int)
2969      * @since 1.8.6
2970      */
2971     @Deprecated
2972     public static <T> List<List<T>> collate( List<T> self, int size ) {
2973         return collate((Iterable<T>) self, size) ;
2974     }
2975 
2976     /**
2977      * Collates this iterable into sub-lists of length <code>size</code> stepping through the code <code>step</code>
2978      * elements for each subList.
2979      * Example:
2980      * <pre class="groovyTestCase">def list = [ 1, 2, 3, 4 ]
2981      * def coll = list.collate( 3, 1 )
2982      * assert coll == [ [ 1, 2, 3 ], [ 2, 3, 4 ], [ 3, 4 ], [ 4 ] ]</pre>
2983      *
2984      * @param self          an Iterable
2985      * @param size          the length of each sub-list in the returned list
2986      * @param step          the number of elements to step through for each sub-list
2987      * @return a List containing the data collated into sub-lists
2988      * @since 2.4.0
2989      */
2990     public static <T> List<List<T>> collate(Iterable<T> self, int size, int step) {
2991         return collate(self, size, step, true);
2992     }
2993 
2994     /**
2995      * @deprecated use the Iterable variant instead
2996      * @see #collate(Iterable, int, int)
2997      * @since 1.8.6
2998      */
2999     @Deprecated
3000     public static <T> List<List<T>> collate( List<T> self, int size, int step ) {
3001         return collate((Iterable<T>) self, size, step) ;
3002     }
3003 
3004     /**
3005      * Collates this iterable into sub-lists of length <code>size</code>. Any remaining elements in
3006      * the iterable after the subdivision will be dropped if <code>keepRemainder</code> is false.
3007      * Example:
3008      * <pre class="groovyTestCase">def list = [ 1, 2, 3, 4, 5, 6, 7 ]
3009      * def coll = list.collate( 3, false )
3010      * assert coll == [ [ 1, 2, 3 ], [ 4, 5, 6 ] ]</pre>
3011      *
3012      * @param self          an Iterable
3013      * @param size          the length of each sub-list in the returned list
3014      * @param keepRemainder if true, any remaining elements are returned as sub-lists.  Otherwise they are discarded
3015      * @return a List containing the data collated into sub-lists
3016      * @since 2.4.0
3017      */
3018     public static <T> List<List<T>> collate(Iterable<T> self, int size, boolean keepRemainder) {
3019         return collate(self, size, size, keepRemainder);
3020     }
3021 
3022     /**
3023      * @deprecated use the Iterable variant instead
3024      * @see #collate(Iterable, int, boolean)
3025      * @since 1.8.6
3026      */
3027     @Deprecated
3028     public static <T> List<List<T>> collate( List<T> self, int size, boolean keepRemainder ) {
3029         return collate((Iterable<T>) self, size, keepRemainder) ;
3030     }
3031 
3032     /**
3033      * Collates this iterable into sub-lists of length <code>size</code> stepping through the code <code>step</code>
3034      * elements for each sub-list.  Any remaining elements in the iterable after the subdivision will be dropped if
3035      * <code>keepRemainder</code> is false.
3036      * Example:
3037      * <pre class="groovyTestCase">
3038      * def list = [ 1, 2, 3, 4 ]
3039      * assert list.collate( 2, 2, true  ) == [ [ 1, 2 ], [ 3, 4 ] ]
3040      * assert list.collate( 3, 1, true  ) == [ [ 1, 2, 3 ], [ 2, 3, 4 ], [ 3, 4 ], [ 4 ] ]
3041      * assert list.collate( 3, 1, false ) == [ [ 1, 2, 3 ], [ 2, 3, 4 ] ]
3042      * </pre>
3043      *
3044      * @param self          an Iterable
3045      * @param size          the length of each sub-list in the returned list
3046      * @param step          the number of elements to step through for each sub-list
3047      * @param keepRemainder if true, any remaining elements are returned as sub-lists.  Otherwise they are discarded
3048      * @return a List containing the data collated into sub-lists
3049      * @since 2.4.0
3050      */
3051     public static <T> List<List<T>> collate(Iterable<T> self, int size, int step, boolean keepRemainder) {
3052         List<T> selfList = asList(self);
3053         List<List<T>> answer = new ArrayList<List<T>>();
3054         if (size <= 0 || selfList.size() == 0) {
3055             answer.add(selfList);
3056         } else {
3057             for (int pos = 0; pos < selfList.size() && pos > -1; pos += step) {
3058                 if (!keepRemainder && pos > selfList.size() - size) {
3059                     break ;
3060                 }
3061                 List<T> element = new ArrayList<T>() ;
3062                 for (int offs = pos; offs < pos + size && offs < selfList.size(); offs++) {
3063                     element.add(selfList.get(offs));
3064                 }
3065                 answer.add( element ) ;
3066             }
3067         }
3068         return answer ;
3069     }
3070 
3071     /**
3072      * @deprecated use the Iterable variant instead
3073      * @see #collate(Iterable, int, int, boolean)
3074      * @since 1.8.6
3075      */
3076     @Deprecated
3077     public static <T> List<List<T>> collate( List<T> self, int size, int step, boolean keepRemainder ) {
3078         return collate((Iterable<T>) self, size, step, keepRemainder);
3079     }
3080 
3081     /**
3082      * Iterates through this aggregate Object transforming each item into a new value using the
3083      * <code>transform</code> closure, returning a list of transformed values.
3084      * Example:
3085      * <pre class="groovyTestCase">def list = [1, 'a', 1.23, true ]
3086      * def types = list.collect { it.class }
3087      * assert types == [Integer, String, BigDecimal, Boolean]</pre>
3088      *
3089      * @param self      an aggregate Object with an Iterator returning its items
3090      * @param transform the closure used to transform each item of the aggregate object
3091      * @return a List of the transformed values
3092      * @since 1.0
3093      */
3094     public static <T> List<T> collect(Object self, Closure<T> transform) {
3095         return (List<T>) collect(self, new ArrayList<T>(), transform);
3096     }
3097 
3098     /**
3099      * Iterates through this aggregate Object transforming each item into a new value using Closure.IDENTITY
3100      * as a transformer, basically returning a list of items copied from the original object.
3101      * <pre class="groovyTestCase">assert [1,2,3] == [1,2,3].iterator().collect()</pre>
3102      *
3103      * @param self an aggregate Object with an Iterator returning its items
3104      * @return a List of the transformed values
3105      * @see Closure#IDENTITY
3106      * @since 1.8.5
3107      */
3108     public static Collection collect(Object self) {
3109         return collect(self, Closure.IDENTITY);
3110     }
3111 
3112     /**
3113      * Iterates through this aggregate Object transforming each item into a new value using the <code>transform</code> closure
3114      * and adding it to the supplied <code>collector</code>.
3115      *
3116      * @param self      an aggregate Object with an Iterator returning its items
3117      * @param collector the Collection to which the transformed values are added
3118      * @param transform the closure used to transform each item of the aggregate object
3119      * @return the collector with all transformed values added to it
3120      * @since 1.0
3121      */
3122     public static <T> Collection<T> collect(Object self, Collection<T> collector, Closure<? extends T> transform) {
3123         for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext(); ) {
3124             collector.add(transform.call(iter.next()));
3125         }
3126         return collector;
3127     }
3128 
3129     /**
3130      * Iterates through this collection transforming each entry into a new value using the <code>transform</code> closure
3131      * returning a list of transformed values.
3132      * <pre class="groovyTestCase">assert [2,4,6] == [1,2,3].collect { it * 2 }</pre>
3133      *
3134      * @param self      a collection
3135      * @param transform the closure used to transform each item of the collection
3136      * @return a List of the transformed values
3137      * @since 1.0
3138      */
3139     public static <S,T> List<T> collect(Collection<S> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure<T> transform) {
3140         return (List<T>) collect(self, new ArrayList<T>(self.size()), transform);
3141     }
3142 
3143     /**
3144      * Iterates through this collection transforming each entry into a new value using Closure.IDENTITY
3145      * as a transformer, basically returning a list of items copied from the original collection.
3146      * <pre class="groovyTestCase">assert [1,2,3] == [1,2,3].collect()</pre>
3147      *
3148      * @param self    a collection
3149      * @return a List of the transformed values
3150      * @since 1.8.5
3151      * @see Closure#IDENTITY
3152      */
3153     public static <T> List<T> collect(Collection<T> self) {
3154         return (List<T>) collect(self, Closure.IDENTITY);
3155     }
3156 
3157     /**
3158      * Iterates through this collection transforming each value into a new value using the <code>transform</code> closure
3159      * and adding it to the supplied <code>collector</code>.
3160      * <pre class="groovyTestCase">assert [1,2,3] as HashSet == [2,4,5,6].collect(new HashSet()) { (int)(it / 2) }</pre>
3161      *
3162      * @param self      a collection
3163      * @param collector the Collection to which the transformed values are added
3164      * @param transform the closure used to transform each item of the collection
3165      * @return the collector with all transformed values added to it
3166      * @since 1.0
3167      */
3168     public static <T,E> Collection<T> collect(Collection<E> self, Collection<T> collector, @ClosureParams(FirstParam.FirstGenericType.class) Closure<? extends T> transform) {
3169         for (E item : self) {
3170             collector.add(transform.call(item));
3171             if (transform.getDirective() == Closure.DONE) {
3172                 break;
3173             }
3174         }
3175         return collector;
3176     }
3177 
3178     /**
3179      * Deprecated alias for collectNested
3180      *
3181      * @deprecated Use collectNested instead
3182      * @see #collectNested(Collection, Closure)
3183      */
3184     @Deprecated
3185     public static List collectAll(Collection self, Closure transform) {
3186         return collectNested(self, transform);
3187     }
3188 
3189     /**
3190      * Recursively iterates through this collection transforming each non-Collection value
3191      * into a new value using the closure as a transformer. Returns a potentially nested
3192      * list of transformed values.
3193      * <pre class="groovyTestCase">
3194      * assert [2,[4,6],[8],[]] == [1,[2,3],[4],[]].collectNested { it * 2 }
3195      * </pre>
3196      *
3197      * @param self      a collection
3198      * @param transform the closure used to transform each item of the collection
3199      * @return the resultant collection
3200      * @since 1.8.1
3201      */
3202     public static List collectNested(Collection self, Closure transform) {
3203         return (List) collectNested((Iterable) self, new ArrayList(self.size()), transform);
3204     }
3205 
3206     /**
3207      * Recursively iterates through this Iterable transforming each non-Collection value
3208      * into a new value using the closure as a transformer. Returns a potentially nested
3209      * list of transformed values.
3210      * <pre class="groovyTestCase">
3211      * assert [2,[4,6],[8],[]] == [1,[2,3],[4],[]].collectNested { it * 2 }
3212      * </pre>
3213      *
3214      * @param self      an Iterable
3215      * @param transform the closure used to transform each item of the Iterable
3216      * @return the resultant list
3217      * @since 2.2.0
3218      */
3219     public static List collectNested(Iterable self, Closure transform) {
3220         return (List) collectNested(self, new ArrayList(), transform);
3221     }
3222 
3223     /**
3224      * Deprecated alias for collectNested
3225      *
3226      * @deprecated Use collectNested instead
3227      * @see #collectNested(Iterable, Collection, Closure)
3228      */
3229     @Deprecated
3230     public static Collection collectAll(Collection self, Collection collector, Closure transform) {
3231         return collectNested((Iterable)self, collector, transform);
3232     }
3233 
3234     /**
3235      * @deprecated Use the Iterable version of collectNested instead
3236      * @see #collectNested(Iterable, Collection, Closure)
3237      * @since 1.8.1
3238      */
3239     @Deprecated
3240     public static Collection collectNested(Collection self, Collection collector, Closure transform) {
3241         return collectNested((Iterable)self, collector, transform);
3242     }
3243 
3244     /**
3245      * Recursively iterates through this Iterable transforming each non-Collection value
3246      * into a new value using the <code>transform</code> closure. Returns a potentially nested
3247      * collection of transformed values.
3248      * <pre class="groovyTestCase">
3249      * def x = [1,[2,3],[4],[]].collectNested(new Vector()) { it * 2 }
3250      * assert x == [2,[4,6],[8],[]]
3251      * assert x instanceof Vector
3252      * </pre>
3253      *
3254      * @param self      an Iterable
3255      * @param collector an initial Collection to which the transformed values are added
3256      * @param transform the closure used to transform each element of the Iterable
3257      * @return the collector with all transformed values added to it
3258      * @since 2.2.0
3259      */
3260     public static Collection collectNested(Iterable self, Collection collector, Closure transform) {
3261         for (Object item : self) {
3262             if (item instanceof Collection) {
3263                 Collection c = (Collection) item;
3264                 collector.add(collectNested((Iterable)c, createSimilarCollection(collector, c.size()), transform));
3265             } else {
3266                 collector.add(transform.call(item));
3267             }
3268             if (transform.getDirective() == Closure.DONE) {
3269                 break;
3270             }
3271         }
3272         return collector;
3273     }
3274 
3275     /**
3276      * @deprecated Use the Iterable version of collectMany instead
3277      * @see #collectMany(Iterable, Closure)
3278      * @since 1.8.1
3279      */
3280     @Deprecated
3281     public static <T,E> List<T> collectMany(Collection<E> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure<Collection<? extends T>> projection) {
3282         return collectMany((Iterable)self, projection);
3283     }
3284 
3285     /**
3286      * @deprecated Use the Iterable version of collectMany instead
3287      * @see #collectMany(Iterable, Collection, Closure)
3288      * @since 1.8.5
3289      */
3290     @Deprecated
3291     public static <T,E> Collection<T> collectMany(Collection<E> self, Collection<T> collector, @ClosureParams(FirstParam.FirstGenericType.class) Closure<Collection<? extends T>> projection) {
3292         return collectMany((Iterable)self, collector, projection);
3293     }
3294 
3295     /**
3296      * Projects each item from a source Iterable to a collection and concatenates (flattens) the resulting collections into a single list.
3297      * <p>
3298      * <pre class="groovyTestCase">
3299      * def nums = 1..10
3300      * def squaresAndCubesOfEvens = nums.collectMany{ it % 2 ? [] : [it**2, it**3] }
3301      * assert squaresAndCubesOfEvens == [4, 8, 16, 64, 36, 216, 64, 512, 100, 1000]
3302      *
3303      * def animals = ['CAT', 'DOG', 'ELEPHANT'] as Set
3304      * def smallAnimals = animals.collectMany{ it.size() > 3 ? [] : [it.toLowerCase()] }
3305      * assert smallAnimals == ['cat', 'dog']
3306      *
3307      * def orig = nums as Set
3308      * def origPlusIncrements = orig.collectMany{ [it, it+1] }
3309      * assert origPlusIncrements.size() == orig.size() * 2
3310      * assert origPlusIncrements.unique().size() == orig.size() + 1
3311      * </pre>
3312      *
3313      * @param self       an Iterable
3314      * @param projection a projecting Closure returning a collection of items
3315      * @return a list created from the projected collections concatenated (flattened) together
3316      * @see #sum(java.util.Collection, groovy.lang.Closure)
3317      * @since 2.2.0
3318      */
3319     public static <T,E> List<T> collectMany(Iterable<E> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure<Collection<? extends T>> projection) {
3320         return (List<T>) collectMany(self, new ArrayList<T>(), projection);
3321     }
3322 
3323     /**
3324      * Projects each item from a source collection to a result collection and concatenates (flattens) the resulting
3325      * collections adding them into the <code>collector</code>.
3326      * <p>
3327      * <pre class="groovyTestCase">
3328      * def animals = ['CAT', 'DOG', 'ELEPHANT'] as Set
3329      * def smallAnimals = animals.collectMany(['ant', 'bee']){ it.size() > 3 ? [] : [it.toLowerCase()] }
3330      * assert smallAnimals == ['ant', 'bee', 'cat', 'dog']
3331      *
3332      * def nums = 1..5
3333      * def origPlusIncrements = nums.collectMany([] as Set){ [it, it+1] }
3334      * assert origPlusIncrements.size() == nums.size() + 1
3335      * </pre>
3336      *
3337      * @param self       an Iterable
3338      * @param collector  an initial collection to add the projected items to
3339      * @param projection a projecting Closure returning a collection of items
3340      * @return the collector with the projected collections concatenated (flattened) into it
3341      * @since 2.2.0
3342      */
3343     public static <T,E> Collection<T> collectMany(Iterable<E> self, Collection<T> collector, @ClosureParams(FirstParam.FirstGenericType.class) Closure<Collection<? extends T>> projection) {
3344         for (E next : self) {
3345             collector.addAll(projection.call(next));
3346         }
3347         return collector;
3348     }
3349 
3350     /**
3351      * Projects each item from a source map to a result collection and concatenates (flattens) the resulting
3352      * collections adding them into the <code>collector</code>.
3353      * <p>
3354      * <pre class="groovyTestCase">
3355      * def map = [bread:3, milk:5, butter:2]
3356      * def result = map.collectMany(['x']){ k, v -> k.startsWith('b') ? k.toList() : [] }
3357      * assert result == ['x', 'b', 'r', 'e', 'a', 'd', 'b', 'u', 't', 't', 'e', 'r']
3358      * </pre>
3359      *
3360      * @param self       a map
3361      * @param collector  an initial collection to add the projected items to
3362      * @param projection a projecting Closure returning a collection of items
3363      * @return the collector with the projected collections concatenated (flattened) to it
3364      * @since 1.8.8
3365      */
3366     public static <T,K,V> Collection<T> collectMany(Map<K, V> self, Collection<T> collector, @ClosureParams(MapEntryOrKeyValue.class) Closure<Collection<? extends T>> projection) {
3367         for (Map.Entry<K, V> entry : self.entrySet()) {
3368             collector.addAll(callClosureForMapEntry(projection, entry));
3369         }
3370         return collector;
3371     }
3372 
3373     /**
3374      * Projects each item from a source map to a result collection and concatenates (flattens) the resulting
3375      * collections adding them into a collection.
3376      * <p>
3377      * <pre class="groovyTestCase">
3378      * def map = [bread:3, milk:5, butter:2]
3379      * def result = map.collectMany{ k, v -> k.startsWith('b') ? k.toList() : [] }
3380      * assert result == ['b', 'r', 'e', 'a', 'd', 'b', 'u', 't', 't', 'e', 'r']
3381      * </pre>
3382      *
3383      * @param self       a map
3384      * @param projection a projecting Closure returning a collection of items
3385      * @return the collector with the projected collections concatenated (flattened) to it
3386      * @since 1.8.8
3387      */
3388     public static <T,K,V> Collection<T> collectMany(Map<K, V> self, @ClosureParams(MapEntryOrKeyValue.class) Closure<Collection<? extends T>> projection) {
3389         return collectMany(self, new ArrayList<T>(), projection);
3390     }
3391 
3392     /**
3393      * Projects each item from a source array to a collection and concatenates (flattens) the resulting collections into a single list.
3394      * <p>
3395      * <pre class="groovyTestCase">
3396      * def nums = [1, 2, 3, 4, 5, 6] as Object[]
3397      * def squaresAndCubesOfEvens = nums.collectMany{ it % 2 ? [] : [it**2, it**3] }
3398      * assert squaresAndCubesOfEvens == [4, 8, 16, 64, 36, 216]
3399      * </pre>
3400      *
3401      * @param self       an array
3402      * @param projection a projecting Closure returning a collection of items
3403      * @return a list created from the projected collections concatenated (flattened) together
3404      * @see #sum(Object[], groovy.lang.Closure)
3405      * @since 1.8.1
3406      */
3407     @SuppressWarnings("unchecked")
3408     public static <T,E> List<T> collectMany(E[] self, @ClosureParams(FirstParam.Component.class) Closure<Collection<? extends T>> projection) {
3409         return collectMany((Iterable<E>)toList(self), projection);
3410     }
3411 
3412     /**
3413      * Projects each item from a source iterator to a collection and concatenates (flattens) the resulting collections into a single list.
3414      * <p>
3415      * <pre class="groovyTestCase">
3416      * def numsIter = [1, 2, 3, 4, 5, 6].iterator()
3417      * def squaresAndCubesOfEvens = numsIter.collectMany{ it % 2 ? [] : [it**2, it**3] }
3418      * assert squaresAndCubesOfEvens == [4, 8, 16, 64, 36, 216]
3419      * </pre>
3420      *
3421      * @param self       an iterator
3422      * @param projection a projecting Closure returning a collection of items
3423      * @return a list created from the projected collections concatenated (flattened) together
3424      * @see #sum(Iterator, groovy.lang.Closure)
3425      * @since 1.8.1
3426      */
3427     @SuppressWarnings("unchecked")
3428     public static <T,E> List<T> collectMany(Iterator<E> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure<Collection<? extends T>> projection) {
3429         return collectMany((Iterable)toList(self), projection);
3430     }
3431 
3432     /**
3433      * Iterates through this Map transforming each map entry into a new value using the <code>transform</code> closure
3434      * returning the <code>collector</code> with all transformed values added to it.
3435      * <pre class="groovyTestCase">assert [a:1, b:2].collect( [] as HashSet ) { key, value -> key*value } == ["a", "bb"] as Set
3436      * assert [3:20, 2:30].collect( [] as HashSet ) { entry -> entry.key * entry.value } == [60] as Set</pre>
3437      *
3438      * @param self      a Map
3439      * @param collector the Collection to which transformed values are added
3440      * @param transform the transformation closure which can take one (Map.Entry) or two (key, value) parameters
3441      * @return the collector with all transformed values added to it
3442      * @since 1.0
3443      */
3444     public static <T,K,V> Collection<T> collect(Map<K, V> self, Collection<T> collector, @ClosureParams(MapEntryOrKeyValue.class) Closure<? extends T> transform) {
3445         for (Map.Entry<K, V> entry : self.entrySet()) {
3446             collector.add(callClosureForMapEntry(transform, entry));
3447         }
3448         return collector;
3449     }
3450 
3451     /**
3452      * Iterates through this Map transforming each map entry into a new value using the <code>transform</code> closure
3453      * returning a list of transformed values.
3454      * <pre class="groovyTestCase">assert [a:1, b:2].collect { key, value -> key*value } == ["a", "bb"]
3455      * assert [3:20, 2:30].collect { entry -> entry.key * entry.value } == [60, 60]</pre>
3456      *
3457      * @param self    a Map
3458      * @param transform the transformation closure which can take one (Map.Entry) or two (key, value) parameters
3459      * @return the resultant list of transformed values
3460      * @since 1.0
3461      */
3462     public static <T,K,V> List<T> collect(Map<K,V> self, @ClosureParams(MapEntryOrKeyValue.class) Closure<T> transform) {
3463         return (List<T>) collect(self, new ArrayList<T>(self.size()), transform);
3464     }
3465 
3466     /**
3467      * Iterates through this Map transforming each map entry using the <code>transform</code> closure
3468      * returning a map of the transformed entries.
3469      * <pre class="groovyTestCase">
3470      * assert [a:1, b:2].collectEntries( [:] ) { k, v -> [v, k] } == [1:'a', 2:'b']
3471      * assert [a:1, b:2].collectEntries( [30:'C'] ) { key, value ->
3472      *     [(value*10): key.toUpperCase()] } == [10:'A', 20:'B', 30:'C']
3473      * </pre>
3474      * Note: When using the list-style of result, the behavior is '<code>def (key, value) = listResultFromClosure</code>'.
3475      * While we strongly discourage using a list of size other than 2, Groovy's normal semantics apply in this case;
3476      * throwing away elements after the second one and using null for the key or value for the case of a shortened list.
3477      * If your collector Map doesn't support null keys or values, you might get a runtime error, e.g. NullPointerException or IllegalArgumentException.
3478      *
3479      * @param self      a Map
3480      * @param collector the Map into which the transformed entries are put
3481      * @param transform the closure used for transforming, which can take one (Map.Entry) or two (key, value) parameters and
3482      *                  should return a Map.Entry, a Map or a two-element list containing the resulting key and value
3483      * @return the collector with all transformed values added to it
3484      * @see #collect(Map, Collection, Closure)
3485      * @since 1.7.9
3486      */
3487     public static <K, V, S, T> Map<K, V> collectEntries(Map<S, T> self, Map<K, V> collector, @ClosureParams(MapEntryOrKeyValue.class) Closure<?> transform) {
3488         for (Map.Entry<S, T> entry : self.entrySet()) {
3489             addEntry(collector, callClosureForMapEntry(transform, entry));
3490         }
3491         return collector;
3492     }
3493 
3494     /**
3495      * Iterates through this Map transforming each entry using the <code>transform</code> closure
3496      * and returning a map of the transformed entries.
3497      * <pre class="groovyTestCase">
3498      * assert [a:1, b:2].collectEntries { key, value -> [value, key] } == [1:'a', 2:'b']
3499      * assert [a:1, b:2].collectEntries { key, value ->
3500      *     [(value*10): key.toUpperCase()] } == [10:'A', 20:'B']
3501      * </pre>
3502      * Note: When using the list-style of result, the behavior is '<code>def (key, value) = listResultFromClosure</code>'.
3503      * While we strongly discourage using a list of size other than 2, Groovy's normal semantics apply in this case;
3504      * throwing away elements after the second one and using null for the key or value for the case of a shortened list.
3505      * If your Map doesn't support null keys or values, you might get a runtime error, e.g. NullPointerException or IllegalArgumentException.
3506      *
3507      * @param self      a Map
3508      * @param transform the closure used for transforming, which can take one (Map.Entry) or two (key, value) parameters and
3509      *                  should return a Map.Entry, a Map or a two-element list containing the resulting key and value
3510      * @return a Map of the transformed entries
3511      * @see #collect(Map, Collection, Closure)
3512      * @since 1.7.9
3513      */
3514     public static <K,V> Map<?, ?> collectEntries(Map<K, V> self, @ClosureParams(MapEntryOrKeyValue.class) Closure<?> transform) {
3515         return collectEntries(self, createSimilarMap(self), transform);
3516     }
3517 
3518     /**
3519      * @deprecated Use the Iterable version of collectEntries instead
3520      * @see #collectEntries(Iterable, Closure)
3521      * @since 1.7.9
3522      */
3523     @Deprecated
3524     public static <K, V> Map<K, V> collectEntries(Collection<?> self, Closure<?> transform) {
3525         return collectEntries((Iterable)self, new LinkedHashMap<K, V>(), transform);
3526     }
3527 
3528     /**
3529      * A variant of collectEntries for Iterators.
3530      *
3531      * @param self      an Iterator
3532      * @param transform the closure used for transforming, which has an item from self as the parameter and
3533      *                  should return a Map.Entry, a Map or a two-element list containing the resulting key and value
3534      * @return a Map of the transformed entries
3535      * @see #collectEntries(Iterable, Closure)
3536      * @since 1.8.7
3537      */
3538     public static <K, V, E> Map<K, V> collectEntries(Iterator<E> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure<?> transform) {
3539         return collectEntries(self, new LinkedHashMap<K, V>(), transform);
3540     }
3541 
3542     /**
3543      * Iterates through this Iterable transforming each item using the <code>transform</code> closure
3544      * and returning a map of the resulting transformed entries.
3545      * <pre class="groovyTestCase">
3546      * def letters = "abc"
3547      * // collect letters with index using list style
3548      * assert (0..2).collectEntries { index -> [index, letters[index]] } == [0:'a', 1:'b', 2:'c']
3549      * // collect letters with index using map style
3550      * assert (0..2).collectEntries { index -> [(index): letters[index]] } == [0:'a', 1:'b', 2:'c']
3551      * </pre>
3552      * Note: When using the list-style of result, the behavior is '<code>def (key, value) = listResultFromClosure</code>'.
3553      * While we strongly discourage using a list of size other than 2, Groovy's normal semantics apply in this case;
3554      * throwing away elements after the second one and using null for the key or value for the case of a shortened list.
3555      *
3556      * @param self      an Iterable
3557      * @param transform the closure used for transforming, which has an item from self as the parameter and
3558      *                  should return a Map.Entry, a Map or a two-element list containing the resulting key and value
3559      * @return a Map of the transformed entries
3560      * @see #collectEntries(Iterator, Closure)
3561      * @since 1.8.7
3562      */
3563     public static <K,V,E> Map<K, V> collectEntries(Iterable<E> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure<?> transform) {
3564         return collectEntries(self.iterator(), transform);
3565     }
3566 
3567     /**
3568      * @deprecated Use the Iterable version of collectEntries instead
3569      * @see #collectEntries(Iterable)
3570      * @since 1.8.5
3571      */
3572     @Deprecated
3573     public static <K, V> Map<K, V> collectEntries(Collection<?> self) {
3574         return collectEntries((Iterable)self, new LinkedHashMap<K, V>(), Closure.IDENTITY);
3575     }
3576 
3577     /**
3578      * A variant of collectEntries for Iterators using the identity closure as the transform.
3579      *
3580      * @param self an Iterator
3581      * @return a Map of the transformed entries
3582      * @see #collectEntries(Iterable)
3583      * @since 1.8.7
3584      */
3585     public static <K, V> Map<K, V> collectEntries(Iterator<?> self) {
3586         return collectEntries(self, Closure.IDENTITY);
3587     }
3588 
3589     /**
3590      * A variant of collectEntries for Iterable objects using the identity closure as the transform.
3591      * The source Iterable should contain a list of <code>[key, value]</code> tuples or <code>Map.Entry</code> objects.
3592      * <pre class="groovyTestCase">
3593      * def nums = [1, 10, 100, 1000]
3594      * def tuples = nums.collect{ [it, it.toString().size()] }
3595      * assert tuples == [[1, 1], [10, 2], [100, 3], [1000, 4]]
3596      * def map = tuples.collectEntries()
3597      * assert map == [1:1, 10:2, 100:3, 1000:4]
3598      * </pre>
3599      *
3600      * @param self an Iterable
3601      * @return a Map of the transformed entries
3602      * @see #collectEntries(Iterator)
3603      * @since 1.8.7
3604      */
3605     public static <K, V> Map<K, V> collectEntries(Iterable<?> self) {
3606         return collectEntries(self.iterator());
3607     }
3608 
3609     /**
3610      * @deprecated Use the Iterable version of collectEntries instead
3611      * @see #collectEntries(Iterable, Map, Closure)
3612      * @since 1.7.9
3613      */
3614     @Deprecated
3615     public static <K, V> Map<K, V> collectEntries(Collection<?> self, Map<K, V> collector, Closure<?> transform) {
3616         return collectEntries((Iterable<?>)self, collector, transform);
3617     }
3618 
3619     /**
3620      * A variant of collectEntries for Iterators using a supplied map as the destination of transformed entries.
3621      *
3622      * @param self      an Iterator
3623      * @param collector the Map into which the transformed entries are put
3624      * @param transform the closure used for transforming, which has an item from self as the parameter and
3625      *                  should return a Map.Entry, a Map or a two-element list containing the resulting key and value
3626      * @return the collector with all transformed values added to it
3627      * @since 1.8.7
3628      */
3629     public static <K, V, E> Map<K, V> collectEntries(Iterator<E> self, Map<K, V> collector, @ClosureParams(FirstParam.FirstGenericType.class) Closure<?> transform) {
3630         while (self.hasNext()) {
3631             E next = self.next();
3632             addEntry(collector, transform.call(next));
3633         }
3634         return collector;
3635     }
3636 
3637     /**
3638      * Iterates through this Iterable transforming each item using the closure
3639      * as a transformer into a map entry, returning the supplied map with all of the transformed entries added to it.
3640      * <pre class="groovyTestCase">
3641      * def letters = "abc"
3642      * // collect letters with index
3643      * assert (0..2).collectEntries( [:] ) { index -> [index, letters[index]] } == [0:'a', 1:'b', 2:'c']
3644      * assert (0..2).collectEntries( [4:'d'] ) { index ->
3645      *     [(index+1): letters[index]] } == [1:'a', 2:'b', 3:'c', 4:'d']
3646      * </pre>
3647      * Note: When using the list-style of result, the behavior is '<code>def (key, value) = listResultFromClosure</code>'.
3648      * While we strongly discourage using a list of size other than 2, Groovy's normal semantics apply in this case;
3649      * throwing away elements after the second one and using null for the key or value for the case of a shortened list.
3650      * If your collector Map doesn't support null keys or values, you might get a runtime error, e.g. NullPointerException or IllegalArgumentException.
3651      *
3652      * @param self      an Iterable
3653      * @param collector the Map into which the transformed entries are put
3654      * @param transform the closure used for transforming, which has an item from self as the parameter and
3655      *                  should return a Map.Entry, a Map or a two-element list containing the resulting key and value
3656      * @return the collector with all transformed values added to it
3657      * @see #collectEntries(Iterator, Map, Closure)
3658      * @since 1.8.7
3659      */
3660     public static <K, V, E> Map<K, V> collectEntries(Iterable<E> self, Map<K, V> collector, @ClosureParams(FirstParam.FirstGenericType.class) Closure<?> transform) {
3661         return collectEntries(self.iterator(), collector, transform);
3662     }
3663 
3664     /**
3665      * @deprecated Use the Iterable version of collectEntries instead
3666      * @see #collectEntries(Iterable, Map)
3667      * @since 1.8.5
3668      */
3669     @Deprecated
3670     public static <K, V> Map<K, V> collectEntries(Collection<?> self, Map<K, V> collector) {
3671         return collectEntries((Iterable<?>)self, collector, Closure.IDENTITY);
3672     }
3673 
3674     /**
3675      * A variant of collectEntries for Iterators using the identity closure as the
3676      * transform and a supplied map as the destination of transformed entries.
3677      *
3678      * @param self      an Iterator
3679      * @param collector the Map into which the transformed entries are put
3680      * @return the collector with all transformed values added to it
3681      * @see #collectEntries(Iterable, Map)
3682      * @since 1.8.7
3683      */
3684     public static <K, V> Map<K, V> collectEntries(Iterator<?> self, Map<K, V> collector) {
3685         return collectEntries(self, collector, Closure.IDENTITY);
3686     }
3687 
3688     /**
3689      * A variant of collectEntries for Iterables using the identity closure as the
3690      * transform and a supplied map as the destination of transformed entries.
3691      *
3692      * @param self      an Iterable
3693      * @param collector the Map into which the transformed entries are put
3694      * @return the collector with all transformed values added to it
3695      * @see #collectEntries(Iterator, Map)
3696      * @since 1.8.7
3697      */
3698     public static <K, V> Map<K, V> collectEntries(Iterable<?> self, Map<K, V> collector) {
3699         return collectEntries(self.iterator(), collector);
3700     }
3701 
3702     /**
3703      * Iterates through this array transforming each item using the <code>transform</code> closure
3704      * and returning a map of the resulting transformed entries.
3705      * <pre class="groovyTestCase">
3706      * def letters = "abc"
3707      * def nums = [0, 1, 2] as Integer[]
3708      * // collect letters with index
3709      * assert nums.collectEntries( [:] ) { index -> [index, letters[index]] } == [0:'a', 1:'b', 2:'c']
3710      * assert nums.collectEntries( [4:'d'] ) { index ->
3711      *     [(index+1): letters[index]] } == [1:'a', 2:'b', 3:'c', 4:'d']
3712      * </pre>
3713      * Note: When using the list-style of result, the behavior is '<code>def (key, value) = listResultFromClosure</code>'.
3714      * While we strongly discourage using a list of size other than 2, Groovy's normal semantics apply in this case;
3715      * throwing away elements after the second one and using null for the key or value for the case of a shortened list.
3716      * If your collector Map doesn't support null keys or values, you might get a runtime error, e.g. NullPointerException or IllegalArgumentException.
3717      *
3718      * @param self      an array
3719      * @param collector the Map into which the transformed entries are put
3720      * @param transform the closure used for transforming, which has an item from self as the parameter and
3721      *                  should return a Map.Entry, a Map or a two-element list containing the resulting key and value
3722      * @return the collector with all transformed values added to it
3723      * @see #collect(Map, Collection, Closure)
3724      * @since 1.7.9
3725      */
3726     @SuppressWarnings("unchecked")
3727     public static <K, V, E> Map<K, V> collectEntries(E[] self, Map<K, V> collector, @ClosureParams(FirstParam.Component.class) Closure<?> transform) {
3728         return collectEntries((Iterable)toList(self), collector, transform);
3729     }
3730 
3731     /**
3732      * A variant of collectEntries using the identity closure as the transform.
3733      *
3734      * @param self      an array
3735      * @param collector the Map into which the transformed entries are put
3736      * @return the collector with all transformed values added to it
3737      * @see #collectEntries(Object[], Map, Closure)
3738      * @since 1.8.5
3739      */
3740     public static <K, V, E> Map<K, V> collectEntries(E[] self, Map<K, V> collector) {
3741         return collectEntries(self, collector, Closure.IDENTITY);
3742     }
3743 
3744     /**
3745      * Iterates through this array transforming each item using the <code>transform</code> closure
3746      * and returning a map of the resulting transformed entries.
3747      * <pre class="groovyTestCase">
3748      * def letters = "abc"
3749      * def nums = [0, 1, 2] as Integer[]
3750      * // collect letters with index using list style
3751      * assert nums.collectEntries { index -> [index, letters[index]] } == [0:'a', 1:'b', 2:'c']
3752      * // collect letters with index using map style
3753      * assert nums.collectEntries { index -> [(index): letters[index]] } == [0:'a', 1:'b', 2:'c']
3754      * </pre>
3755      * Note: When using the list-style of result, the behavior is '<code>def (key, value) = listResultFromClosure</code>'.
3756      * While we strongly discourage using a list of size other than 2, Groovy's normal semantics apply in this case;
3757      * throwing away elements after the second one and using null for the key or value for the case of a shortened list.
3758      *
3759      * @param self      a Collection
3760      * @param transform the closure used for transforming, which has an item from self as the parameter and
3761      *                  should return a Map.Entry, a Map or a two-element list containing the resulting key and value
3762      * @return a Map of the transformed entries
3763      * @see #collectEntries(Iterable, Map, Closure)
3764      * @since 1.7.9
3765      */
3766     public static <K, V, E> Map<K, V> collectEntries(E[] self, @ClosureParams(FirstParam.Component.class) Closure<?> transform) {
3767         return collectEntries((Iterable)toList(self), new LinkedHashMap<K, V>(), transform);
3768     }
3769 
3770     /**
3771      * A variant of collectEntries using the identity closure as the transform.
3772      *
3773      * @param self      an array
3774      * @return the collector with all transformed values added to it
3775      * @see #collectEntries(Object[], Closure)
3776      * @since 1.8.5
3777      */
3778     public static <K, V, E> Map<K, V> collectEntries(E[] self) {
3779         return collectEntries(self, Closure.IDENTITY);
3780     }
3781 
3782     private static <K, V> void addEntry(Map<K, V> result, Object newEntry) {
3783         if (newEntry instanceof Map) {
3784             leftShift(result, (Map)newEntry);
3785         } else if (newEntry instanceof List) {
3786             List list = (List) newEntry;
3787             // def (key, value) == list
3788             Object key = list.size() == 0 ? null : list.get(0);
3789             Object value = list.size() <= 1 ? null : list.get(1);
3790             leftShift(result, new MapEntry(key, value));
3791         } else {
3792             // TODO: enforce stricter behavior?
3793             // given Map.Entry is an interface, we get a proxy which gives us lots
3794             // of flexibility but sometimes the error messages might be unexpected
3795             leftShift(result, asType(newEntry, Map.Entry.class));
3796         }
3797     }
3798 
3799     /**
3800      * Finds the first value matching the closure condition
3801      *
3802      * @param self    an Object with an iterator returning its values
3803      * @param closure a closure condition
3804      * @return the first Object found or null if none was found
3805      * @since 1.0
3806      */
3807     public static Object find(Object self, Closure closure) {
3808         BooleanClosureWrapper bcw = new BooleanClosureWrapper(closure);
3809         for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext();) {
3810             Object value = iter.next();
3811             if (bcw.call(value)) {
3812                 return value;
3813             }
3814         }
3815         return null;
3816     }
3817 
3818     /**
3819      * Finds the first item matching the IDENTITY Closure (i.e.&#160;matching Groovy truth).
3820      * <p>
3821      * Example:
3822      * <pre class="groovyTestCase">
3823      * def items = [null, 0, 0.0, false, '', [], 42, 43]
3824      * assert items.find() == 42
3825      * </pre>
3826      *
3827      * @param self    an Object with an Iterator returning its values
3828      * @return the first Object found or null if none was found
3829      * @since 1.8.1
3830      * @see Closure#IDENTITY
3831      */
3832     public static Object find(Object self) {
3833         return find(self, Closure.IDENTITY);
3834     }
3835 
3836     /**
3837      * Treats the object as iterable, iterating through the values it represents and returns the first non-null result obtained from calling the closure, otherwise returns the defaultResult.
3838      *
3839      * @param self    an Object with an iterator returning its values
3840      * @param defaultResult an Object that should be returned if all closure results are null
3841      * @param closure a closure that returns a non-null value when processing should stop
3842      * @return the first non-null result of the closure, otherwise the default value
3843      * @since 1.7.5
3844      */
3845     public static Object findResult(Object self, Object defaultResult, Closure closure) {
3846         Object result = findResult(self, closure);
3847         if (result == null) return defaultResult;
3848         return result;
3849     }
3850 
3851     /**
3852      * Treats the object as iterable, iterating through the values it represents and returns the first non-null result obtained from calling the closure, otherwise returns null.
3853      *
3854      * @param self    an Object with an iterator returning its values
3855      * @param closure a closure that returns a non-null value when processing should stop
3856      * @return the first non-null result of the closure
3857      * @since 1.7.5
3858      */
3859     public static Object findResult(Object self, Closure closure) {
3860         for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext();) {
3861             Object value = iter.next();
3862             Object result = closure.call(value);
3863             if (result != null) {
3864                 return result;
3865             }
3866         }
3867         return null;
3868     }
3869 
3870     /**
3871      * Finds the first value matching the closure condition.  Example:
3872      * <pre class="groovyTestCase">def list = [1,2,3]
3873      * assert 2 == list.find { it > 1 }
3874      * </pre>
3875      *
3876      * @param self    a Collection
3877      * @param closure a closure condition
3878      * @return the first Object found, in the order of the collections iterator, or null if no element matches
3879      * @since 1.0
3880      */
3881     public static <T> T find(Collection<T> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure closure) {
3882         BooleanClosureWrapper bcw = new BooleanClosureWrapper(closure);
3883         for (T value : self) {
3884             if (bcw.call(value)) {
3885                 return value;
3886             }
3887         }
3888         return null;
3889     }
3890 
3891     /**
3892      * Finds the first element in the array that matches the given closure condition.
3893      * Example:
3894      * <pre class="groovyTestCase">
3895      * def list = [1,2,3] as Integer[]
3896      * assert 2 == list.find { it > 1 }
3897      * assert null == list.find { it > 5 }
3898      * </pre>
3899      *
3900      * @param self      an Array
3901      * @param condition a closure condition
3902      * @return the first element from the array that matches the condition or null if no element matches
3903      * @since 2.0
3904      */
3905     public static <T> T find(T[] self, @ClosureParams(FirstParam.Component.class) Closure condition) {
3906         BooleanClosureWrapper bcw = new BooleanClosureWrapper(condition);
3907         for (T element : self) {
3908             if (bcw.call(element)) {
3909                 return element;
3910             }
3911         }
3912         return null;
3913     }
3914 
3915     /**
3916      * Finds the first item matching the IDENTITY Closure (i.e.&#160;matching Groovy truth).
3917      * <p>
3918      * Example:
3919      * <pre class="groovyTestCase">
3920      * def items = [null, 0, 0.0, false, '', [], 42, 43]
3921      * assert items.find() == 42
3922      * </pre>
3923      *
3924      * @param self    a Collection
3925      * @return the first Object found or null if none was found
3926      * @since 1.8.1
3927      * @see Closure#IDENTITY
3928      */
3929     public static <T> T find(Collection<T> self) {
3930         return find(self, Closure.IDENTITY);
3931     }
3932 
3933     /**
3934      * Iterates through the collection calling the given closure for each item but stopping once the first non-null
3935      * result is found and returning that result. If all are null, the defaultResult is returned.
3936      * <p>
3937      * Examples:
3938      * <pre class="groovyTestCase">
3939      * def list = [1,2,3]
3940      * assert "Found 2" == list.findResult("default") { it > 1 ? "Found $it" : null }
3941      * assert "default" == list.findResult("default") { it > 3 ? "Found $it" : null }
3942      * </pre>
3943      *
3944      * @param self          a Collection
3945      * @param defaultResult an Object that should be returned if all closure results are null
3946      * @param closure a closure that returns a non-null value when processing should stop and a value should be returned
3947      * @return the first non-null result from calling the closure, or the defaultValue
3948      * @since 1.7.5
3949      */
3950     public static <T, U extends T, V extends T,E> T findResult(Collection<E> self, U defaultResult, @ClosureParams(FirstParam.FirstGenericType.class) Closure<V> closure) {
3951         T result = findResult(self, closure);
3952         if (result == null) return defaultResult;
3953         return result;
3954     }
3955 
3956     /**
3957      * Iterates through the collection calling the given closure for each item but stopping once the first non-null
3958      * result is found and returning that result. If all results are null, null is returned.
3959      * <p>
3960      * Example:
3961      * <pre class="groovyTestCase">
3962      * def list = [1,2,3]
3963      * assert "Found 2" == list.findResult { it > 1 ? "Found $it" : null }
3964      * </pre>
3965      *
3966      * @param self    a Collection
3967      * @param closure a closure that returns a non-null value when processing should stop and a value should be returned
3968      * @return the first non-null result from calling the closure, or null
3969      * @since 1.7.5
3970      */
3971     public static <T,U> T findResult(Collection<U> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure<T> closure) {
3972         for (Object value : self) {
3973             T result = closure.call(value);
3974             if (result != null) {
3975                 return result;
3976             }
3977         }
3978         return null;
3979     }
3980 
3981     /**
3982      * @deprecated Use the Iterable version of findResults instead
3983      * @see #findResults(Iterable, Closure)
3984      * @since 1.8.1
3985      */
3986     @Deprecated
3987     public static <T,U> Collection<T> findResults(Collection<U> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure<T> filteringTransform) {
3988         return findResults((Iterable<?>)self, filteringTransform);
3989     }
3990 
3991     /**
3992      * Iterates through the Iterable transforming items using the supplied closure
3993      * and collecting any non-null results.
3994      * <p>
3995      * Example:
3996      * <pre class="groovyTestCase">
3997      * def list = [1,2,3]
3998      * def result = list.findResults { it > 1 ? "Found $it" : null }
3999      * assert result == ["Found 2", "Found 3"]
4000      * </pre>
4001      *
4002      * @param self               an Iterable
4003      * @param filteringTransform a Closure that should return either a non-null transformed value or null for items which should be discarded
4004      * @return the list of non-null transformed values
4005      * @since 2.2.0
4006      */
4007     public static <T,U> Collection<T> findResults(Iterable<U> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure<T> filteringTransform) {
4008         List<T> result = new ArrayList<T>();
4009         for (Object value : self) {
4010             T transformed = filteringTransform.call(value);
4011             if (transformed != null) {
4012                 result.add(transformed);
4013             }
4014         }
4015         return result;
4016     }
4017 
4018     /**
4019      * Iterates through the map transforming items using the supplied closure
4020      * and collecting any non-null results.
4021      * If the closure takes two parameters, the entry key and value are passed.
4022      * If the closure takes one parameter, the Map.Entry object is passed.
4023      * <p>
4024      * Example:
4025      * <pre class="groovyTestCase">
4026      * def map = [a:1, b:2, hi:2, cat:3, dog:2]
4027      * def result = map.findResults { k, v -> k.size() == v ? "Found $k:$v" : null }
4028      * assert result == ["Found a:1", "Found hi:2", "Found cat:3"]
4029      * </pre>
4030      *
4031      * @param self               a Map
4032      * @param filteringTransform a 1 or 2 arg Closure that should return either a non-null transformed value or null for items which should be discarded
4033      * @return the list of non-null transformed values
4034      * @since 1.8.1
4035      */
4036     public static <T,K,V> Collection<T> findResults(Map<K, V> self, @ClosureParams(MapEntryOrKeyValue.class) Closure<T> filteringTransform) {
4037         List<T> result = new ArrayList<T>();
4038         for (Map.Entry<K, V> entry : self.entrySet()) {
4039             T transformed = callClosureForMapEntry(filteringTransform, entry);
4040             if (transformed != null) {
4041                 result.add(transformed);
4042             }
4043         }
4044         return result;
4045     }
4046 
4047     /**
4048      * Finds the first entry matching the closure condition.
4049      * If the closure takes two parameters, the entry key and value are passed.
4050      * If the closure takes one parameter, the Map.Entry object is passed.
4051      * <pre class="groovyTestCase">assert [a:1, b:3].find { it.value == 3 }.key == "b"</pre>
4052      *
4053      * @param self    a Map
4054      * @param closure a 1 or 2 arg Closure condition
4055      * @return the first Object found
4056      * @since 1.0
4057      */
4058     public static <K, V> Map.Entry<K, V> find(Map<K, V> self, @ClosureParams(MapEntryOrKeyValue.class) Closure<?> closure) {
4059         BooleanClosureWrapper bcw = new BooleanClosureWrapper(closure);
4060         for (Map.Entry<K, V> entry : self.entrySet()) {
4061             if (bcw.callForMap(entry)) {
4062                 return entry;
4063             }
4064         }
4065         return null;
4066     }
4067 
4068     /**
4069      * Returns the first non-null closure result found by passing each map entry to the closure, otherwise the defaultResult is returned.
4070      * If the closure takes two parameters, the entry key and value are passed.
4071      * If the closure takes one parameter, the Map.Entry object is passed.
4072      * <pre class="groovyTestCase">
4073      * assert "Found b:3" == [a:1, b:3].findResult("default") { if (it.value == 3) return "Found ${it.key}:${it.value}" }
4074      * assert "default" == [a:1, b:3].findResult("default") { if (it.value == 9) return "Found ${it.key}:${it.value}" }
4075      * assert "Found a:1" == [a:1, b:3].findResult("default") { k, v -> if (k.size() + v == 2) return "Found $k:$v" }
4076      * </pre>
4077      *
4078      * @param self    a Map
4079      * @param defaultResult an Object that should be returned if all closure results are null
4080      * @param closure a 1 or 2 arg Closure that returns a non-null value when processing should stop and a value should be returned
4081      * @return the first non-null result collected by calling the closure, or the defaultResult if no such result was found
4082      * @since 1.7.5
4083      */
4084     public static <T, U extends T, V extends T,A,B> T findResult(Map<A, B> self, U defaultResult, @ClosureParams(MapEntryOrKeyValue.class) Closure<V> closure) {
4085         T result = findResult(self, closure);
4086         if (result == null) return defaultResult;
4087         return result;
4088     }
4089 
4090     /**
4091      * Returns the first non-null closure result found by passing each map entry to the closure, otherwise null is returned.
4092      * If the closure takes two parameters, the entry key and value are passed.
4093      * If the closure takes one parameter, the Map.Entry object is passed.
4094      * <pre class="groovyTestCase">
4095      * assert "Found b:3" == [a:1, b:3].findResult { if (it.value == 3) return "Found ${it.key}:${it.value}" }
4096      * assert null == [a:1, b:3].findResult { if (it.value == 9) return "Found ${it.key}:${it.value}" }
4097      * assert "Found a:1" == [a:1, b:3].findResult { k, v -> if (k.size() + v == 2) return "Found $k:$v" }
4098      * </pre>
4099      *
4100      * @param self    a Map
4101      * @param closure a 1 or 2 arg Closure that returns a non-null value when processing should stop and a value should be returned
4102      * @return the first non-null result collected by calling the closure, or null if no such result was found
4103      * @since 1.7.5
4104      */
4105     public static <T,K,V> T findResult(Map<K, V> self, @ClosureParams(MapEntryOrKeyValue.class) Closure<T> closure) {
4106         for (Map.Entry<K, V> entry : self.entrySet()) {
4107             T result = callClosureForMapEntry(closure, entry);
4108             if (result != null) {
4109                 return result;
4110             }
4111         }
4112         return null;
4113     }
4114 
4115     /**
4116      * Finds all values matching the closure condition.
4117      * <pre class="groovyTestCase">assert ([2,4] as Set) == ([1,2,3,4] as Set).findAll { it % 2 == 0 }</pre>
4118      *
4119      * @param self    a Set
4120      * @param closure a closure condition
4121      * @return a Set of matching values
4122      * @since 2.4.0
4123      */
4124     public static <T> Set<T> findAll(Set<T> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure closure) {
4125         return (Set<T>) findAll((Collection<T>) self, closure);
4126     }
4127 
4128     /**
4129      * Finds all values matching the closure condition.
4130      * <pre class="groovyTestCase">assert [2,4] == [1,2,3,4].findAll { it % 2 == 0 }</pre>
4131      *
4132      * @param self    a List
4133      * @param closure a closure condition
4134      * @return a List of matching values
4135      * @since 2.4.0
4136      */
4137     public static <T> List<T> findAll(List<T> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure closure) {
4138         return (List<T>) findAll((Collection<T>) self, closure);
4139     }
4140 
4141     /**
4142      * Finds all values matching the closure condition.
4143      * <pre class="groovyTestCase">assert [2,4] == [1,2,3,4].findAll { it % 2 == 0 }</pre>
4144      *
4145      * @param self    a Collection
4146      * @param closure a closure condition
4147      * @return a Collection of matching values
4148      * @since 1.5.6
4149      */
4150     public static <T> Collection<T> findAll(Collection<T> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure closure) {
4151         Collection<T> answer = createSimilarCollection(self);
4152         Iterator<T> iter = self.iterator();
4153         return findAll(closure, answer, iter);
4154     }
4155 
4156     /**
4157      * Finds all elements of the array matching the given Closure condition.
4158      * <pre class="groovyTestCase">
4159      * def items = [1,2,3,4] as Integer[]
4160      * assert [2,4] == items.findAll { it % 2 == 0 }
4161      * </pre>
4162      *
4163      * @param self      an array
4164      * @param condition a closure condition
4165      * @return a list of matching values
4166      * @since 2.0
4167      */
4168     public static <T> Collection<T> findAll(T[] self, @ClosureParams(FirstParam.Component.class) Closure condition) {
4169         Collection<T> answer = new ArrayList<T>();
4170         return findAll(condition, answer, new ArrayIterator<T>(self));
4171     }
4172 
4173     /**
4174      * Finds the items matching the IDENTITY Closure (i.e.&#160;matching Groovy truth).
4175      * <p>
4176      * Example:
4177      * <pre class="groovyTestCase">
4178      * def items = [1, 2, 0, false, true, '', 'foo', [], [4, 5], null] as Set
4179      * assert items.findAll() == [1, 2, true, 'foo', [4, 5]] as Set
4180      * </pre>
4181      *
4182      * @param self    a Set
4183      * @return a Set of the values found
4184      * @since 2.4.0
4185      * @see Closure#IDENTITY
4186      */
4187     public static <T> Set<T> findAll(Set<T> self) {
4188         return findAll(self, Closure.IDENTITY);
4189     }
4190 
4191     /**
4192      * Finds the items matching the IDENTITY Closure (i.e.&#160;matching Groovy truth).
4193      * <p>
4194      * Example:
4195      * <pre class="groovyTestCase">
4196      * def items = [1, 2, 0, false, true, '', 'foo', [], [4, 5], null]
4197      * assert items.findAll() == [1, 2, true, 'foo', [4, 5]]
4198      * </pre>
4199      *
4200      * @param self    a List
4201      * @return a List of the values found
4202      * @since 2.4.0
4203      * @see Closure#IDENTITY
4204      */
4205     public static <T> List<T> findAll(List<T> self) {
4206         return findAll(self, Closure.IDENTITY);
4207     }
4208 
4209     /**
4210      * Finds the items matching the IDENTITY Closure (i.e.&#160;matching Groovy truth).
4211      * <p>
4212      * Example:
4213      * <pre class="groovyTestCase">
4214      * def items = [1, 2, 0, false, true, '', 'foo', [], [4, 5], null]
4215      * assert items.findAll() == [1, 2, true, 'foo', [4, 5]]
4216      * </pre>
4217      *
4218      * @param self    a Collection
4219      * @return a Collection of the values found
4220      * @since 1.8.1
4221      * @see Closure#IDENTITY
4222      */
4223     public static <T> Collection<T> findAll(Collection<T> self) {
4224         return findAll(self, Closure.IDENTITY);
4225     }
4226 
4227     /**
4228      * Finds the elements of the array matching the IDENTITY Closure (i.e.&#160;matching Groovy truth).
4229      * <p>
4230      * Example:
4231      * <pre class="groovyTestCase">
4232      * def items = [1, 2, 0, false, true, '', 'foo', [], [4, 5], null] as Object[]
4233      * assert items.findAll() == [1, 2, true, 'foo', [4, 5]]
4234      * </pre>
4235      *
4236      * @param self an array
4237      * @return a collection of the elements found
4238      * @see Closure#IDENTITY
4239      * @since 2.0
4240      */
4241     public static <T> Collection<T> findAll(T[] self) {
4242         return findAll(self, Closure.IDENTITY);
4243     }
4244 
4245     /**
4246      * Finds all items matching the closure condition.
4247      *
4248      * @param self    an Object with an Iterator returning its values
4249      * @param closure a closure condition
4250      * @return a List of the values found
4251      * @since 1.6.0
4252      */
4253     public static Collection findAll(Object self, Closure closure) {
4254         List answer = new ArrayList();
4255         Iterator iter = InvokerHelper.asIterator(self);
4256         return findAll(closure, answer, iter);
4257     }
4258 
4259     /**
4260      * Finds all items matching the IDENTITY Closure (i.e.&#160;matching Groovy truth).
4261      * <p>
4262      * Example:
4263      * <pre class="groovyTestCase">
4264      * def items = [1, 2, 0, false, true, '', 'foo', [], [4, 5], null]
4265      * assert items.findAll() == [1, 2, true, 'foo', [4, 5]]
4266      * </pre>
4267      *
4268      * @param self    an Object with an Iterator returning its values
4269      * @return a List of the values found
4270      * @since 1.8.1
4271      * @see Closure#IDENTITY
4272      */
4273     public static Collection findAll(Object self) {
4274         return findAll(self, Closure.IDENTITY);
4275     }
4276 
4277     private static <T> Collection<T> findAll(Closure closure, Collection<T> answer, Iterator<? extends T> iter) {
4278         BooleanClosureWrapper bcw = new BooleanClosureWrapper(closure);
4279         while (iter.hasNext()) {
4280             T value = iter.next();
4281             if (bcw.call(value)) {
4282                 answer.add(value);
4283             }
4284         }
4285         return answer;
4286     }
4287 
4288     /**
4289      * Returns <tt>true</tt> if this iterable contains the item.
4290      *
4291      * @param  self an Iterable to be checked for containment
4292      * @param  item an Object to be checked for containment in this iterable
4293      * @return <tt>true</tt> if this iterable contains the item
4294      * @see    Collection#contains(Object)
4295      * @since 2.4.0
4296      */
4297     public static boolean contains(Iterable self, Object item) {
4298         for (Object e : self) {
4299             if (item == null ? e == null : item.equals(e)) {
4300                 return true;
4301             }
4302         }
4303         return false;
4304     }
4305 
4306     /**
4307      * Returns <tt>true</tt> if this iterable contains all of the elements
4308      * in the specified array.
4309      *
4310      * @param  self  an Iterable to be checked for containment
4311      * @param  items array to be checked for containment in this iterable
4312      * @return <tt>true</tt> if this collection contains all of the elements
4313      *           in the specified array
4314      * @see    Collection#containsAll(Collection)
4315      * @since 2.4.0
4316      */
4317     public static boolean containsAll(Iterable self, Object[] items) {
4318         return asCollection(self).containsAll(Arrays.asList(items));
4319     }
4320 
4321     /**
4322      * @deprecated use the Iterable variant instead
4323      * @see #containsAll(Iterable, Object[])
4324      * @since 1.7.2
4325      */
4326     @Deprecated
4327     public static boolean containsAll(Collection self, Object[] items) {
4328         return self.containsAll(Arrays.asList(items));
4329     }
4330 
4331     /**
4332      * Modifies this collection by removing its elements that are contained
4333      * within the specified object array.
4334      *
4335      * See also <code>findAll</code> and <code>grep</code> when wanting to produce a new list
4336      * containing items which don't match some criteria while leaving the original collection unchanged.
4337      *
4338      * @param  self  a Collection to be modified
4339      * @param  items array containing elements to be removed from this collection
4340      * @return <tt>true</tt> if this collection changed as a result of the call
4341      * @see    Collection#removeAll(Collection)
4342      * @since 1.7.2
4343      */
4344     public static boolean removeAll(Collection self, Object[] items) {
4345         Collection pickFrom = new TreeSet(new NumberAwareComparator());
4346         pickFrom.addAll(Arrays.asList(items));
4347         return self.removeAll(pickFrom);
4348     }
4349 
4350     /**
4351      * Modifies this collection so that it retains only its elements that are contained
4352      * in the specified array.  In other words, removes from this collection all of
4353      * its elements that are not contained in the specified array.
4354      *
4355      * See also <code>grep</code> and <code>findAll</code> when wanting to produce a new list
4356      * containing items which match some specified items but leaving the original collection unchanged.
4357      *
4358      * @param  self  a Collection to be modified
4359      * @param  items array containing elements to be retained from this collection
4360      * @return <tt>true</tt> if this collection changed as a result of the call
4361      * @see    Collection#retainAll(Collection)
4362      * @since 1.7.2
4363      */
4364     public static boolean retainAll(Collection self, Object[] items) {
4365         Collection pickFrom = new TreeSet(new NumberAwareComparator());
4366         pickFrom.addAll(Arrays.asList(items));
4367         return self.retainAll(pickFrom);
4368     }
4369 
4370     /**
4371      * Modifies this collection so that it retains only its elements
4372      * that are matched according to the specified closure condition.  In other words,
4373      * removes from this collection all of its elements that don't match.
4374      *
4375      * See also <code>findAll</code> and <code>grep</code> when wanting to produce a new list
4376      * containing items which match some criteria but leaving the original collection unchanged.
4377      *
4378      * @param  self      a Collection to be modified
4379      * @param  condition a closure condition
4380      * @return <tt>true</tt> if this collection changed as a result of the call
4381      * @see    Iterator#remove()
4382      * @since 1.7.2
4383      */
4384     public static <T> boolean retainAll(Collection<T> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure condition) {
4385         Iterator iter = InvokerHelper.asIterator(self);
4386         BooleanClosureWrapper bcw = new BooleanClosureWrapper(condition);
4387         boolean result = false;
4388         while (iter.hasNext()) {
4389             Object value = iter.next();
4390             if (!bcw.call(value)) {
4391                 iter.remove();
4392                 result = true;
4393             }
4394         }
4395         return result;
4396     }
4397 
4398     /**
4399      * Modifies this collection by removing the elements that are matched according
4400      * to the specified closure condition.
4401      *
4402      * See also <code>findAll</code> and <code>grep</code> when wanting to produce a new list
4403      * containing items which don't match some criteria while leaving the original collection unchanged.
4404      *
4405      * @param  self a Collection to be modified
4406      * @param  condition a closure condition
4407      * @return <tt>true</tt> if this collection changed as a result of the call
4408      * @see    Iterator#remove()
4409      * @since 1.7.2
4410      */
4411     public static <T> boolean removeAll(Collection<T> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure condition) {
4412         Iterator iter = InvokerHelper.asIterator(self);
4413         BooleanClosureWrapper bcw = new BooleanClosureWrapper(condition);
4414         boolean result = false;
4415         while (iter.hasNext()) {
4416             Object value = iter.next();
4417             if (bcw.call(value)) {
4418                 iter.remove();
4419                 result = true;
4420             }
4421         }
4422         return result;
4423     }
4424 
4425     /**
4426      * Modifies the collection by adding all of the elements in the specified array to the collection.
4427      * The behavior of this operation is undefined if
4428      * the specified array is modified while the operation is in progress.
4429      *
4430      * See also <code>plus</code> or the '+' operator if wanting to produce a new collection
4431      * containing additional items but while leaving the original collection unchanged.
4432      *
4433      * @param  self  a Collection to be modified
4434      * @param  items array containing elements to be added to this collection
4435      * @return <tt>true</tt> if this collection changed as a result of the call
4436      * @see    Collection#addAll(Collection)
4437      * @since 1.7.2
4438      */
4439     public static <T> boolean addAll(Collection<T> self, T[] items) {
4440         return self.addAll(Arrays.asList(items));
4441     }
4442 
4443     /**
4444      * Modifies this list by inserting all of the elements in the specified array into the
4445      * list at the specified position.  Shifts the
4446      * element currently at that position (if any) and any subsequent
4447      * elements to the right (increases their indices).  The new elements
4448      * will appear in this list in the order that they occur in the array.
4449      * The behavior of this operation is undefined if the specified array
4450      * is modified while the operation is in progress.
4451      *
4452      * See also <code>plus</code> for similar functionality with copy semantics, i.e. which produces a new
4453      * list after adding the additional items at the specified position but leaves the original list unchanged.
4454      *
4455      * @param self  a list to be modified
4456      * @param items array containing elements to be added to this collection
4457      * @param index index at which to insert the first element from the
4458      *              specified array
4459      * @return <tt>true</tt> if this collection changed as a result of the call
4460      * @see    List#addAll(int, Collection)
4461      * @since 1.7.2
4462      */
4463     public static <T> boolean addAll(List<T> self, int index, T[] items) {
4464         return self.addAll(index, Arrays.asList(items));
4465     }
4466 
4467     /**
4468      * Splits all items into two lists based on the closure condition.
4469      * The first list contains all items matching the closure expression.
4470      * The second list all those that don't.
4471      *
4472      * @param self    an Object with an Iterator returning its values
4473      * @param closure a closure condition
4474      * @return a List whose first item is the accepted values and whose second item is the rejected values
4475      * @since 1.6.0
4476      */
4477     public static Collection split(Object self, Closure closure) {
4478         List accept = new ArrayList();
4479         List reject = new ArrayList();
4480         return split(closure, accept, reject, InvokerHelper.asIterator(self));
4481     }
4482 
4483     /**
4484      * Splits all items into two collections based on the closure condition.
4485      * The first list contains all items which match the closure expression.
4486      * The second list all those that don't.
4487      * <p>
4488      * Example usage:
4489      * <pre class="groovyTestCase">assert [[2,4],[1,3]] == [1,2,3,4].split { it % 2 == 0 }</pre>
4490      *
4491      * @param self    a Collection of values
4492      * @param closure a closure condition
4493      * @return a List whose first item is the accepted values and whose second item is the rejected values
4494      * @since 1.6.0
4495      */
4496     public static <T> Collection<Collection<T>> split(Collection<T> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure closure) {
4497         Collection<T> accept = createSimilarCollection(self);
4498         Collection<T> reject = createSimilarCollection(self);
4499         Iterator<T> iter = self.iterator();
4500         return split(closure, accept, reject, iter);
4501     }
4502 
4503     private static <T> Collection<Collection<T>> split(Closure closure, Collection<T> accept, Collection<T> reject, Iterator<T> iter) {
4504         List<Collection<T>> answer = new ArrayList<Collection<T>>();
4505         BooleanClosureWrapper bcw = new BooleanClosureWrapper(closure);
4506         while (iter.hasNext()) {
4507             T value = iter.next();
4508             if (bcw.call(value)) {
4509                 accept.add(value);
4510             } else {
4511                 reject.add(value);
4512             }
4513         }
4514         answer.add(accept);
4515         answer.add(reject);
4516         return answer;
4517     }
4518 
4519     /**
4520      * Splits all items into two collections based on the closure condition.
4521      * The first list contains all items which match the closure expression.
4522      * The second list all those that don't.
4523      * <p>
4524      * Example usage:
4525      * <pre class="groovyTestCase">assert [[2,4],[1,3]] == [1,2,3,4].split { it % 2 == 0 }</pre>
4526      *
4527      * @param self    a List of values
4528      * @param closure a closure condition
4529      * @return a List whose first item is the accepted values and whose second item is the rejected values
4530      * @since 2.4.0
4531      */
4532     @SuppressWarnings("unchecked")
4533     public static <T> List<List<T>> split(List<T> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure closure) {
4534         return (List<List<T>>) (List<?>) split((Collection<T>) self, closure);
4535     }
4536 
4537     /**
4538      * Splits all items into two collections based on the closure condition.
4539      * The first list contains all items which match the closure expression.
4540      * The second list all those that don't.
4541      * <p>
4542      * Example usage:
4543      * <pre class="groovyTestCase">assert [[2,4] as Set, [1,3] as Set] == ([1,2,3,4] as Set).split { it % 2 == 0 }</pre>
4544      *
4545      * @param self    a Set of values
4546      * @param closure a closure condition
4547      * @return a List whose first item is the accepted values and whose second item is the rejected values
4548      * @since 2.4.0
4549      */
4550     @SuppressWarnings("unchecked")
4551     public static <T> List<Set<T>> split(Set<T> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure closure) {
4552         return (List<Set<T>>) (List<?>) split((Collection<T>) self, closure);
4553     }
4554 
4555     /**
4556      * @deprecated Use the Iterable version of combinations instead
4557      * @see #combinations(Iterable)
4558      * @since 1.5.0
4559      */
4560     @Deprecated
4561     public static List combinations(Collection self) {
4562         return combinations((Iterable)self);
4563     }
4564 
4565     /**
4566      * Adds GroovyCollections#combinations(Iterable) as a method on Iterables.
4567      * <p>
4568      * Example usage:
4569      * <pre class="groovyTestCase">
4570      * assert [['a', 'b'],[1, 2, 3]].combinations() == [['a', 1], ['b', 1], ['a', 2], ['b', 2], ['a', 3], ['b', 3]]
4571      * </pre>
4572      *
4573      * @param self an Iterable of collections
4574      * @return a List of the combinations found
4575      * @see groovy.util.GroovyCollections#combinations(java.lang.Iterable)
4576      * @since 2.2.0
4577      */
4578     public static List combinations(Iterable self) {
4579         return GroovyCollections.combinations(self);
4580     }
4581 
4582 
4583     /**
4584      * Adds GroovyCollections#combinations(Iterable, Closure) as a method on collections.
4585      * <p>
4586      * Example usage:
4587      * <pre class="groovyTestCase">assert [[2, 3],[4, 5, 6]].combinations {x,y -> x*y } == [8, 12, 10, 15, 12, 18]</pre>
4588      *
4589      * @param self a Collection of lists
4590      * @param function a closure to be called on each combination
4591      * @return a List of the results of applying the closure to each combinations found
4592      * @see groovy.util.GroovyCollections#combinations(Iterable)
4593      * @since 2.2.0
4594      */
4595     public static List combinations(Iterable self, Closure<?> function) {
4596         return collect(GroovyCollections.combinations(self), function);
4597     }
4598 
4599     /**
4600      * Applies a function on each combination of the input lists.
4601      * <p>
4602      * Example usage:
4603      * <pre class="groovyTestCase">[[2, 3],[4, 5, 6]].eachCombination { println "Found $it" }</pre>
4604      *
4605      * @param self a Collection of lists
4606      * @param function a closure to be called on each combination
4607      * @see groovy.util.GroovyCollections#combinations(Iterable)
4608      * @since 2.2.0
4609      */
4610     public static void eachCombination(Iterable self, Closure<?> function) {
4611         each(GroovyCollections.combinations(self), function);
4612     }
4613 
4614     /**
4615      * Finds all non-null subsequences of a list.
4616      * <p>
4617      * Example usage:
4618      * <pre class="groovyTestCase">def result = [1, 2, 3].subsequences()
4619      * assert result == [[1, 2, 3], [1, 3], [2, 3], [1, 2], [1], [2], [3]] as Set</pre>
4620      *
4621      * @param self the List of items
4622      * @return the subsequences from the list
4623      * @since 1.7.0
4624      */
4625     public static <T> Set<List<T>> subsequences(List<T> self) {
4626         return GroovyCollections.subsequences(self);
4627     }
4628 
4629     /**
4630      * Finds all permutations of an iterable.
4631      * <p>
4632      * Example usage:
4633      * <pre class="groovyTestCase">def result = [1, 2, 3].permutations()
4634      * assert result == [[3, 2, 1], [3, 1, 2], [1, 3, 2], [2, 3, 1], [2, 1, 3], [1, 2, 3]] as Set</pre>
4635      *
4636      * @param self the Iterable of items
4637      * @return the permutations from the list
4638      * @since 1.7.0
4639      */
4640     public static <T> Set<List<T>> permutations(Iterable<T> self) {
4641         Set<List<T>> ans = new HashSet<List<T>>();
4642         PermutationGenerator<T> generator = new PermutationGenerator<T>(self);
4643         while (generator.hasNext()) {
4644             ans.add(generator.next());
4645         }
4646         return ans;
4647     }
4648 
4649     /**
4650      * @deprecated Use the Iterable version of permutations instead
4651      * @see #permutations(Iterable)
4652      * @since 1.7.0
4653      */
4654     @Deprecated
4655     public static <T> Set<List<T>> permutations(List<T> self) {
4656         return permutations((Iterable<T>) self);
4657     }
4658 
4659     /**
4660      * Finds all permutations of an iterable, applies a function to each permutation and collects the result
4661      * into a list.
4662      * <p>
4663      * Example usage:
4664      * <pre class="groovyTestCase">Set result = [1, 2, 3].permutations { it.collect { v -> 2*v }}
4665      * assert result == [[6, 4, 2], [6, 2, 4], [2, 6, 4], [4, 6, 2], [4, 2, 6], [2, 4, 6]] as Set</pre>
4666      *
4667      * @param self the Iterable of items
4668      * @param function the function to apply on each permutation
4669      * @return the list of results of the application of the function on each permutation
4670      * @since 2.2.0
4671      */
4672     public static <T,V> List<V> permutations(Iterable<T> self, Closure<V> function) {
4673         return collect(permutations(self),function);
4674     }
4675 
4676     /**
4677      * @deprecated Use the Iterable version of permutations instead
4678      * @see #permutations(Iterable, Closure)
4679      * @since 2.2.0
4680      */
4681     @Deprecated
4682     public static <T, V> List<V> permutations(List<T> self, Closure<V> function) {
4683         return permutations((Iterable<T>) self, function);
4684     }
4685 
4686     /**
4687      * @deprecated Use the Iterable version of eachPermutation instead
4688      * @see #eachPermutation(Iterable, Closure)
4689      * @since 1.7.0
4690      */
4691     @Deprecated
4692     public static <T> Iterator<List<T>> eachPermutation(Collection<T> self, Closure closure) {
4693         return eachPermutation((Iterable<T>) self, closure);
4694     }
4695 
4696     /**
4697      * Iterates over all permutations of a collection, running a closure for each iteration.
4698      * <p>
4699      * Example usage:
4700      * <pre class="groovyTestCase">def permutations = []
4701      * [1, 2, 3].eachPermutation{ permutations &lt;&lt; it }
4702      * assert permutations == [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]</pre>
4703      *
4704      * @param self the Collection of items
4705      * @param closure the closure to call for each permutation
4706      * @return the permutations from the list
4707      * @since 1.7.0
4708      */
4709     public static <T> Iterator<List<T>> eachPermutation(Iterable<T> self, Closure closure) {
4710         Iterator<List<T>> generator = new PermutationGenerator<T>(self);
4711         while (generator.hasNext()) {
4712             closure.call(generator.next());
4713         }
4714         return generator;
4715     }
4716 
4717     /**
4718      * Adds GroovyCollections#transpose(List) as a method on lists.
4719      * A Transpose Function takes a collection of columns and returns a collection of
4720      * rows. The first row consists of the first element from each column. Successive
4721      * rows are constructed similarly.
4722      * <p>
4723      * Example usage:
4724      * <pre class="groovyTestCase">def result = [['a', 'b'], [1, 2]].transpose()
4725      * assert result == [['a', 1], ['b', 2]]</pre>
4726      * <pre class="groovyTestCase">def result = [['a', 'b'], [1, 2], [3, 4]].transpose()
4727      * assert result == [['a', 1, 3], ['b', 2, 4]]</pre>
4728      *
4729      * @param self a List of lists
4730      * @return a List of the transposed lists
4731      * @see groovy.util.GroovyCollections#transpose(java.util.List)
4732      * @since 1.5.0
4733      */
4734     public static List transpose(List self) {
4735         return GroovyCollections.transpose(self);
4736     }
4737 
4738     /**
4739      * Finds all entries matching the closure condition. If the
4740      * closure takes one parameter then it will be passed the Map.Entry.
4741      * Otherwise if the closure should take two parameters, which will be
4742      * the key and the value.
4743      * <p>
4744      * If the <code>self</code> map is one of TreeMap, LinkedHashMap, Hashtable
4745      * or Properties, the returned Map will preserve that type, otherwise a HashMap will
4746      * be returned.
4747      * <p>
4748      * Example usage:
4749      * <pre class="groovyTestCase">
4750      * def result = [a:1, b:2, c:4, d:5].findAll { it.value % 2 == 0 }
4751      * assert result.every { it instanceof Map.Entry }
4752      * assert result*.key == ["b", "c"]
4753      * assert result*.value == [2, 4]
4754      * </pre>
4755      *
4756      * @param self    a Map
4757      * @param closure a 1 or 2 arg Closure condition applying on the entries
4758      * @return a new subMap
4759      * @since 1.0
4760      */
4761     public static <K, V> Map<K, V> findAll(Map<K, V> self, @ClosureParams(MapEntryOrKeyValue.class)  Closure closure) {
4762         Map<K, V> answer = createSimilarMap(self);
4763         BooleanClosureWrapper bcw = new BooleanClosureWrapper(closure);
4764         for (Map.Entry<K, V> entry : self.entrySet()) {
4765             if (bcw.callForMap(entry)) {
4766                 answer.put(entry.getKey(), entry.getValue());
4767             }
4768         }
4769         return answer;
4770     }
4771 
4772     /**
4773      * @deprecated Use the Iterable version of groupBy instead
4774      * @see #groupBy(Iterable, Closure)
4775      * @since 1.0
4776      */
4777     @Deprecated
4778     public static <K, T> Map<K, List<T>> groupBy(Collection<T> self, Closure<K> closure) {
4779         return groupBy((Iterable<T>)self, closure);
4780     }
4781 
4782     /**
4783      * Sorts all Iterable members into groups determined by the supplied mapping closure.
4784      * The closure should return the key that this item should be grouped by. The returned
4785      * LinkedHashMap will have an entry for each distinct key returned from the closure,
4786      * with each value being a list of items for that group.
4787      * <p>
4788      * Example usage:
4789      * <pre class="groovyTestCase">
4790      * assert [0:[2,4,6], 1:[1,3,5]] == [1,2,3,4,5,6].groupBy { it % 2 }
4791      * </pre>
4792      *
4793      * @param self    a collection to group
4794      * @param closure a closure mapping entries on keys
4795      * @return a new Map grouped by keys
4796      * @since 2.2.0
4797      */
4798     public static <K, T> Map<K, List<T>> groupBy(Iterable<T> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure<K> closure) {
4799         Map<K, List<T>> answer = new LinkedHashMap<K, List<T>>();
4800         for (T element : self) {
4801             K value = closure.call(element);
4802             groupAnswer(answer, element, value);
4803         }
4804         return answer;
4805     }
4806 
4807     /**
4808      * Sorts all array members into groups determined by the supplied mapping closure.
4809      * The closure should return the key that this item should be grouped by. The returned
4810      * LinkedHashMap will have an entry for each distinct key returned from the closure,
4811      * with each value being a list of items for that group.
4812      * <p>
4813      * Example usage:
4814      * <pre class="groovyTestCase">
4815      * Integer[] items = [1,2,3,4,5,6]
4816      * assert [0:[2,4,6], 1:[1,3,5]] == items.groupBy { it % 2 }
4817      * </pre>
4818      *
4819      * @param self    an array to group
4820      * @param closure a closure mapping entries on keys
4821      * @return a new Map grouped by keys
4822      * @see #groupBy(Iterable, Closure)
4823      * @since 2.2.0
4824      */
4825     public static <K, T> Map<K, List<T>> groupBy(T[] self, @ClosureParams(FirstParam.Component.class) Closure<K> closure) {
4826         return groupBy((Iterable<T>)Arrays.asList(self), closure);
4827     }
4828 
4829     /**
4830      * @deprecated Use the Iterable version of groupBy instead
4831      * @see #groupBy(Iterable, Object...)
4832      * @since 1.8.1
4833      */
4834     @Deprecated
4835     public static Map groupBy(Collection self, Object... closures) {
4836         return groupBy((Iterable)self, closures);
4837     }
4838 
4839     /**
4840      * Sorts all Iterable members into (sub)groups determined by the supplied
4841      * mapping closures. Each closure should return the key that this item
4842      * should be grouped by. The returned LinkedHashMap will have an entry for each
4843      * distinct 'key path' returned from the closures, with each value being a list
4844      * of items for that 'group path'.
4845      *
4846      * Example usage:
4847      * <pre class="groovyTestCase">def result = [1,2,3,4,5,6].groupBy({ it % 2 }, { it < 4 })
4848      * assert result == [1:[(true):[1, 3], (false):[5]], 0:[(true):[2], (false):[4, 6]]]</pre>
4849      *
4850      * Another example:
4851      * <pre>def sql = groovy.sql.Sql.newInstance(/&ast; ... &ast;/)
4852      * def data = sql.rows("SELECT * FROM a_table").groupBy({ it.column1 }, { it.column2 }, { it.column3 })
4853      * if (data.val1.val2.val3) {
4854      *     // there exists a record where:
4855      *     //   a_table.column1 == val1
4856      *     //   a_table.column2 == val2, and
4857      *     //   a_table.column3 == val3
4858      * } else {
4859      *     // there is no such record
4860      * }</pre>
4861      * If an empty array of closures is supplied the IDENTITY Closure will be used.
4862      *
4863      * @param self     a collection to group
4864      * @param closures an array of closures, each mapping entries on keys
4865      * @return a new Map grouped by keys on each criterion
4866      * @since 2.2.0
4867      * @see Closure#IDENTITY
4868      */
4869     public static Map groupBy(Iterable self, Object... closures) {
4870         final Closure head = closures.length == 0 ? Closure.IDENTITY : (Closure) closures[0];
4871 
4872         @SuppressWarnings("unchecked")
4873         Map<Object, List> first = groupBy(self, head);
4874         if (closures.length < 2)
4875             return first;
4876 
4877         final Object[] tail = new Object[closures.length - 1];
4878         System.arraycopy(closures, 1, tail, 0, closures.length - 1); // Arrays.copyOfRange only since JDK 1.6
4879 
4880         // inject([:]) { a,e -> a << [(e.key): e.value.groupBy(tail)] }
4881         Map<Object, Map> acc = new LinkedHashMap<Object, Map>();
4882         for (Map.Entry<Object, List> item : first.entrySet()) {
4883             acc.put(item.getKey(), groupBy((Iterable)item.getValue(), tail));
4884         }
4885 
4886         return acc;
4887     }
4888 
4889     /**
4890      * Sorts all array members into (sub)groups determined by the supplied
4891      * mapping closures as per the Iterable variant of this method.
4892      *
4893      * @param self     an array to group
4894      * @param closures an array of closures, each mapping entries on keys
4895      * @return a new Map grouped by keys on each criterion
4896      * @see #groupBy(Iterable, Object...)
4897      * @see Closure#IDENTITY
4898      * @since 2.2.0
4899      */
4900     public static Map groupBy(Object[] self, Object... closures) {
4901         return groupBy((Iterable)Arrays.asList(self), closures);
4902     }
4903 
4904     /**
4905      * @deprecated Use the Iterable version of groupBy instead
4906      * @see #groupBy(Iterable, List)
4907      * @since 1.8.1
4908      */
4909     @Deprecated
4910     public static Map groupBy(Collection self, List<Closure> closures) {
4911         return groupBy((Iterable)self, closures);
4912     }
4913 
4914     /**
4915      * Sorts all Iterable members into (sub)groups determined by the supplied
4916      * mapping closures. Each closure should return the key that this item
4917      * should be grouped by. The returned LinkedHashMap will have an entry for each
4918      * distinct 'key path' returned from the closures, with each value being a list
4919      * of items for that 'group path'.
4920      *
4921      * Example usage:
4922      * <pre class="groovyTestCase">
4923      * def result = [1,2,3,4,5,6].groupBy([{ it % 2 }, { it < 4 }])
4924      * assert result == [1:[(true):[1, 3], (false):[5]], 0:[(true):[2], (false):[4, 6]]]
4925      * </pre>
4926      *
4927      * Another example:
4928      * <pre>
4929      * def sql = groovy.sql.Sql.newInstance(/&ast; ... &ast;/)
4930      * def data = sql.rows("SELECT * FROM a_table").groupBy([{ it.column1 }, { it.column2 }, { it.column3 }])
4931      * if (data.val1.val2.val3) {
4932      *     // there exists a record where:
4933      *     //   a_table.column1 == val1
4934      *     //   a_table.column2 == val2, and
4935      *     //   a_table.column3 == val3
4936      * } else {
4937      *     // there is no such record
4938      * }
4939      * </pre>
4940      * If an empty list of closures is supplied the IDENTITY Closure will be used.
4941      *
4942      * @param self     a collection to group
4943      * @param closures a list of closures, each mapping entries on keys
4944      * @return a new Map grouped by keys on each criterion
4945      * @since 2.2.0
4946      * @see Closure#IDENTITY
4947      */
4948     public static Map groupBy(Iterable self, List<Closure> closures) {
4949         return groupBy(self, closures.toArray());
4950     }
4951 
4952     /**
4953      * Sorts all array members into (sub)groups determined by the supplied
4954      * mapping closures as per the list variant of this method.
4955      *
4956      * @param self     an array to group
4957      * @param closures a list of closures, each mapping entries on keys
4958      * @return a new Map grouped by keys on each criterion
4959      * @see Closure#IDENTITY
4960      * @see #groupBy(Iterable, List)
4961      * @since 2.2.0
4962      */
4963     public static Map groupBy(Object[] self, List<Closure> closures) {
4964         return groupBy((Iterable)Arrays.asList(self), closures);
4965     }
4966 
4967     /**
4968      * @deprecated Use the Iterable version of countBy instead
4969      * @see #countBy(Iterable, Closure)
4970      * @since 1.8.0
4971      */
4972     @Deprecated
4973     public static <K> Map<K, Integer> countBy(Collection self, Closure<K> closure) {
4974         return countBy((Iterable) self, closure);
4975     }
4976 
4977     /**
4978      * Sorts all collection members into groups determined by the supplied mapping
4979      * closure and counts the group size.  The closure should return the key that each
4980      * item should be grouped by.  The returned Map will have an entry for each
4981      * distinct key returned from the closure, with each value being the frequency of
4982      * items occurring for that group.
4983      * <p>
4984      * Example usage:
4985      * <pre class="groovyTestCase">assert [0:2, 1:3] == [1,2,3,4,5].countBy { it % 2 }</pre>
4986      *
4987      * @param self    a collection to group and count
4988      * @param closure a closure mapping items to the frequency keys
4989      * @return a new Map grouped by keys with frequency counts
4990      * @since 2.2.0
4991      */
4992     public static <K,E> Map<K, Integer> countBy(Iterable<E> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure<K> closure) {
4993         return countBy(self.iterator(), closure);
4994     }
4995 
4996     /**
4997      * Sorts all array members into groups determined by the supplied mapping
4998      * closure and counts the group size.  The closure should return the key that each
4999      * item should be grouped by.  The returned Map will have an entry for each
5000      * distinct key returned from the closure, with each value being the frequency of
5001      * items occurring for that group.
5002      * <p>
5003      * Example usage:
5004      * <pre class="groovyTestCase">assert ([1,2,2,2,3] as Object[]).countBy{ it % 2 } == [1:2, 0:3]</pre>
5005      *
5006      * @param self    an array to group and count
5007      * @param closure a closure mapping items to the frequency keys
5008      * @return a new Map grouped by keys with frequency counts
5009      * @see #countBy(Collection, Closure)
5010      * @since 1.8.0
5011      */
5012     public static <K,E> Map<K, Integer> countBy(E[] self, @ClosureParams(FirstParam.Component.class) Closure<K> closure) {
5013         return countBy((Iterable)Arrays.asList(self), closure);
5014     }
5015 
5016     /**
5017      * Sorts all iterator items into groups determined by the supplied mapping
5018      * closure and counts the group size.  The closure should return the key that each
5019      * item should be grouped by.  The returned Map will have an entry for each
5020      * distinct key returned from the closure, with each value being the frequency of
5021      * items occurring for that group.
5022      * <p>
5023      * Example usage:
5024      * <pre class="groovyTestCase">assert [1,2,2,2,3].toSet().iterator().countBy{ it % 2 } == [1:2, 0:1]</pre>
5025      *
5026      * @param self    an iterator to group and count
5027      * @param closure a closure mapping items to the frequency keys
5028      * @return a new Map grouped by keys with frequency counts
5029      * @see #countBy(Collection, Closure)
5030      * @since 1.8.0
5031      */
5032     public static <K,E> Map<K, Integer> countBy(Iterator<E> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure<K> closure) {
5033         Map<K, Integer> answer = new LinkedHashMap<K, Integer>();
5034         while (self.hasNext()) {
5035             K value = closure.call(self.next());
5036             countAnswer(answer, value);
5037         }
5038         return answer;
5039     }
5040 
5041     /**
5042      * Groups all map entries into groups determined by the
5043      * supplied mapping closure. The closure will be passed a Map.Entry or
5044      * key and value (depending on the number of parameters the closure accepts)
5045      * and should return the key that each item should be grouped under.  The
5046      * resulting map will have an entry for each 'group' key returned by the
5047      * closure, with values being the list of map entries that belong to each
5048      * group. (If instead of a list of map entries, you want an actual map
5049      * use {code}groupBy{code}.)
5050      * <pre class="groovyTestCase">def result = [a:1,b:2,c:3,d:4,e:5,f:6].groupEntriesBy { it.value % 2 }
5051      * assert result[0]*.key == ["b", "d", "f"]
5052      * assert result[1]*.value == [1, 3, 5]</pre>
5053      *
5054      * @param self    a map to group
5055      * @param closure a 1 or 2 arg Closure mapping entries on keys
5056      * @return a new Map grouped by keys
5057      * @since 1.5.2
5058      */
5059     public static <G, K, V> Map<G, List<Map.Entry<K, V>>> groupEntriesBy(Map<K, V> self, @ClosureParams(MapEntryOrKeyValue.class) Closure<G> closure) {
5060         final Map<G, List<Map.Entry<K, V>>> answer = new LinkedHashMap<G, List<Map.Entry<K, V>>>();
5061         for (Map.Entry<K, V> entry : self.entrySet()) {
5062             G value = callClosureForMapEntry(closure, entry);
5063             groupAnswer(answer, entry, value);
5064         }
5065         return answer;
5066     }
5067 
5068     /**
5069      * Groups the members of a map into sub maps determined by the
5070      * supplied mapping closure. The closure will be passed a Map.Entry or
5071      * key and value (depending on the number of parameters the closure accepts)
5072      * and should return the key that each item should be grouped under.  The
5073      * resulting map will have an entry for each 'group' key returned by the
5074      * closure, with values being the map members from the original map that
5075      * belong to each group. (If instead of a map, you want a list of map entries
5076      * use {code}groupEntriesBy{code}.)
5077      * <p>
5078      * If the <code>self</code> map is one of TreeMap, Hashtable or Properties,
5079      * the returned Map will preserve that type, otherwise a LinkedHashMap will
5080      * be returned.
5081      * <pre class="groovyTestCase">def result = [a:1,b:2,c:3,d:4,e:5,f:6].groupBy { it.value % 2 }
5082      * assert result == [0:[b:2, d:4, f:6], 1:[a:1, c:3, e:5]]</pre>
5083      *
5084      * @param self    a map to group
5085      * @param closure a closure mapping entries on keys
5086      * @return a new Map grouped by keys
5087      * @since 1.0
5088      */
5089     public static <G, K, V> Map<G, Map<K, V>> groupBy(Map<K, V> self, @ClosureParams(MapEntryOrKeyValue.class) Closure<G> closure) {
5090         final Map<G, List<Map.Entry<K, V>>> initial = groupEntriesBy(self, closure);
5091         final Map<G, Map<K, V>> answer = new LinkedHashMap<G, Map<K, V>>();
5092         for (Map.Entry<G, List<Map.Entry<K, V>>> outer : initial.entrySet()) {
5093             G key = outer.getKey();
5094             List<Map.Entry<K, V>> entries = outer.getValue();
5095             Map<K, V> target = createSimilarMap(self);
5096             putAll(target, entries);
5097             answer.put(key, target);
5098         }
5099         return answer;
5100     }
5101 
5102     /**
5103      * Groups the members of a map into sub maps determined by the supplied
5104      * mapping closures. Each closure will be passed a Map.Entry or key and
5105      * value (depending on the number of parameters the closure accepts) and
5106      * should return the key that each item should be grouped under. The
5107      * resulting map will have an entry for each 'group path' returned by all
5108      * closures, with values being the map members from the original map that
5109      * belong to each such 'group path'.
5110      *
5111      * If the <code>self</code> map is one of TreeMap, Hashtable, or Properties,
5112      * the returned Map will preserve that type, otherwise a LinkedHashMap will
5113      * be returned.
5114      *
5115      * <pre class="groovyTestCase">def result = [a:1,b:2,c:3,d:4,e:5,f:6].groupBy({ it.value % 2 }, { it.key.next() })
5116      * assert result == [1:[b:[a:1], d:[c:3], f:[e:5]], 0:[c:[b:2], e:[d:4], g:[f:6]]]</pre>
5117      * If an empty array of closures is supplied the IDENTITY Closure will be used.
5118      *
5119      * @param self     a map to group
5120      * @param closures an array of closures that map entries on keys
5121      * @return a new map grouped by keys on each criterion
5122      * @since 1.8.1
5123      * @see Closure#IDENTITY
5124      */
5125     public static Map<Object, Map> groupBy(Map self, Object... closures) {
5126         @SuppressWarnings("unchecked")
5127         final Closure<Object> head = closures.length == 0 ? Closure.IDENTITY : (Closure) closures[0];
5128 
5129         @SuppressWarnings("unchecked")
5130         Map<Object, Map> first = groupBy(self, head);
5131         if (closures.length < 2)
5132             return first;
5133 
5134         final Object[] tail = new Object[closures.length - 1];
5135         System.arraycopy(closures, 1, tail, 0, closures.length - 1); // Arrays.copyOfRange only since JDK 1.6
5136 
5137         Map<Object, Map> acc = new LinkedHashMap<Object, Map>();
5138         for (Map.Entry<Object, Map> item: first.entrySet()) {
5139             acc.put(item.getKey(), groupBy(item.getValue(), tail));
5140         }
5141 
5142         return acc;
5143     }
5144 
5145     /**
5146      * Groups the members of a map into sub maps determined by the supplied
5147      * mapping closures. Each closure will be passed a Map.Entry or key and
5148      * value (depending on the number of parameters the closure accepts) and
5149      * should return the key that each item should be grouped under. The
5150      * resulting map will have an entry for each 'group path' returned by all
5151      * closures, with values being the map members from the original map that
5152      * belong to each such 'group path'.
5153      *
5154      * If the <code>self</code> map is one of TreeMap, Hashtable, or Properties,
5155      * the returned Map will preserve that type, otherwise a LinkedHashMap will
5156      * be returned.
5157      *
5158      * <pre class="groovyTestCase">def result = [a:1,b:2,c:3,d:4,e:5,f:6].groupBy([{ it.value % 2 }, { it.key.next() }])
5159      * assert result == [1:[b:[a:1], d:[c:3], f:[e:5]], 0:[c:[b:2], e:[d:4], g:[f:6]]]</pre>
5160      * If an empty list of closures is supplied the IDENTITY Closure will be used.
5161      *
5162      * @param self     a map to group
5163      * @param closures a list of closures that map entries on keys
5164      * @return a new map grouped by keys on each criterion
5165      * @since 1.8.1
5166      * @see Closure#IDENTITY
5167      */
5168     public static Map<Object, Map> groupBy(Map self, List<Closure> closures) {
5169         return groupBy(self, closures.toArray());
5170     }
5171 
5172     /**
5173      * Groups the members of a map into groups determined by the
5174      * supplied mapping closure and counts the frequency of the created groups.
5175      * The closure will be passed a Map.Entry or
5176      * key and value (depending on the number of parameters the closure accepts)
5177      * and should return the key that each item should be grouped under.  The
5178      * resulting map will have an entry for each 'group' key returned by the
5179      * closure, with values being the frequency counts for that 'group'.
5180      * <p>
5181      * <pre class="groovyTestCase">def result = [a:1,b:2,c:3,d:4,e:5].countBy { it.value % 2 }
5182      * assert result == [0:2, 1:3]</pre>
5183      *
5184      * @param self    a map to group and count
5185      * @param closure a closure mapping entries to frequency count keys
5186      * @return a new Map grouped by keys with frequency counts
5187      * @since 1.8.0
5188      */
5189     public static <K,U,V> Map<K, Integer> countBy(Map<U,V> self, @ClosureParams(MapEntryOrKeyValue.class) Closure<K> closure) {
5190         Map<K, Integer> answer = new LinkedHashMap<K, Integer>();
5191         for (Object entry : self.entrySet()) {
5192             countAnswer(answer, callClosureForMapEntry(closure, (Map.Entry) entry));
5193         }
5194         return answer;
5195     }
5196 
5197     /**
5198      * Groups the current element according to the value
5199      *
5200      * @param answer  the map containing the results
5201      * @param element the element to be placed
5202      * @param value   the value according to which the element will be placed
5203      * @since 1.5.0
5204      */
5205     protected static <K, T> void groupAnswer(final Map<K, List<T>> answer, T element, K value) {
5206         if (answer.containsKey(value)) {
5207             answer.get(value).add(element);
5208         } else {
5209             List<T> groupedElements = new ArrayList<T>();
5210             groupedElements.add(element);
5211             answer.put(value, groupedElements);
5212         }
5213     }
5214 
5215     private static <T> void countAnswer(final Map<T, Integer> answer, T mappedKey) {
5216         if (!answer.containsKey(mappedKey)) {
5217             answer.put(mappedKey, 0);
5218         }
5219         int current = answer.get(mappedKey);
5220         answer.put(mappedKey, current + 1);
5221     }
5222 
5223     // internal helper method
5224     protected static <T> T callClosureForMapEntry(Closure<T> closure, Map.Entry entry) {
5225         if (closure.getMaximumNumberOfParameters() == 2) {
5226             return closure.call(new Object[]{entry.getKey(), entry.getValue()});
5227         }
5228         return closure.call(entry);
5229     }
5230 
5231     // internal helper method
5232     protected static <T> T callClosureForLine(Closure<T> closure, String line, int counter) {
5233         if (closure.getMaximumNumberOfParameters() == 2) {
5234             return closure.call(new Object[]{line, counter});
5235         }
5236         return closure.call(line);
5237     }
5238 
5239     // internal helper method
5240     protected static <T> T callClosureForMapEntryAndCounter(Closure<T> closure, Map.Entry entry, int counter) {
5241         if (closure.getMaximumNumberOfParameters() == 3) {
5242             return closure.call(new Object[]{entry.getKey(), entry.getValue(), counter});
5243         }
5244         if (closure.getMaximumNumberOfParameters() == 2) {
5245             return closure.call(new Object[]{entry, counter});
5246         }
5247         return closure.call(entry);
5248     }
5249 
5250 
5251     /**
5252      * Performs the same function as the version of inject that takes an initial value, but
5253      * uses the head of the Collection as the initial value, and iterates over the tail.
5254      * <pre class="groovyTestCase">
5255      * assert 1 * 2 * 3 * 4 == [ 1, 2, 3, 4 ].inject { acc, val -> acc * val }
5256      * assert ['b'] == [['a','b'], ['b','c'], ['d','b']].inject { acc, val -> acc.intersect( val ) }
5257      * LinkedHashSet set = [ 't', 'i', 'm' ]
5258      * assert 'tim' == set.inject { a, b -> a + b }
5259      * </pre>
5260      *
5261      * @param self         a Collection
5262      * @param closure      a closure
5263      * @return the result of the last closure call
5264      * @throws NoSuchElementException if the collection is empty.
5265      * @see #inject(Collection, Object, Closure)
5266      * @since 1.8.7
5267      */
5268     public static <T, V extends T> T inject(Collection<T> self, @ClosureParams(value=FromString.class,options="V,T") Closure<V> closure ) {
5269         if( self.isEmpty() ) {
5270             throw new NoSuchElementException( "Cannot call inject() on an empty collection without passing an initial value." ) ;
5271         }
5272         Iterator<T> iter = self.iterator();
5273         T head = iter.next();
5274         Collection<T> tail = tail(self);
5275         if (!tail.iterator().hasNext()) {
5276             return head;
5277         }
5278         // cast with explicit weaker generics for now to keep jdk6 happy, TODO: find better fix
5279         return (T) inject((Collection) tail, head, closure);
5280     }
5281 
5282     /**
5283      * Iterates through the given Collection, passing in the initial value to
5284      * the 2-arg closure along with the first item. The result is passed back (injected) into
5285      * the closure along with the second item. The new result is injected back into
5286      * the closure along with the third item and so on until the entire collection
5287      * has been used. Also known as <tt>foldLeft</tt> or <tt>reduce</tt> in functional parlance.
5288      *
5289      * Examples:
5290      * <pre class="groovyTestCase">
5291      * assert 1*1*2*3*4 == [1,2,3,4].inject(1) { acc, val -> acc * val }
5292      *
5293      * assert 0+1+2+3+4 == [1,2,3,4].inject(0) { acc, val -> acc + val }
5294      *
5295      * assert 'The quick brown fox' ==
5296      *     ['quick', 'brown', 'fox'].inject('The') { acc, val -> acc + ' ' + val }
5297      *
5298      * assert 'bat' ==
5299      *     ['rat', 'bat', 'cat'].inject('zzz') { min, next -> next < min ? next : min }
5300      *
5301      * def max = { a, b -> [a, b].max() }
5302      * def animals = ['bat', 'rat', 'cat']
5303      * assert 'rat' == animals.inject('aaa', max)
5304      * </pre>
5305      * Visual representation of the last example above:
5306      * <pre>
5307      *    initVal  animals[0]
5308      *       v        v
5309      * max('aaa',   'bat')  =>  'bat'  animals[1]
5310      *                            v       v
5311      *                      max('bat',  'rat')  =>  'rat'  animals[2]
5312      *                                                v       v
5313      *                                          max('rat',  'cat')  =>  'rat'
5314      * </pre>
5315      *
5316      * @param self         a Collection
5317      * @param initialValue some initial value
5318      * @param closure      a closure
5319      * @return the result of the last closure call
5320      * @since 1.0
5321      */
5322     public static <E, T, U extends T, V extends T> T inject(Collection<E> self, U initialValue, @ClosureParams(value=FromString.class,options="U,E") Closure<V> closure) {
5323         // cast with explicit weaker generics for now to keep jdk6 happy, TODO: find better fix
5324         return (T) inject((Iterator) self.iterator(), initialValue, closure);
5325     }
5326 
5327     /**
5328      * Iterates through the given Map, passing in the initial value to
5329      * the 2-arg Closure along with the first item (or 3-arg Closure along with the first key and value).
5330      * The result is passed back (injected) into
5331      * the closure along with the second item. The new result is injected back into
5332      * the closure along with the third item and so on until the entire collection
5333      * has been used. Also known as <tt>foldLeft</tt> or <tt>reduce</tt> in functional parlance.
5334      *
5335      * Examples:
5336      * <pre class="groovyTestCase">
5337      * def map = [a:1, b:2, c:3]
5338      * assert map.inject([]) { list, k, v ->
5339      *   list + [k] * v
5340      * } == ['a', 'b', 'b', 'c', 'c', 'c']
5341      * </pre>
5342      *
5343      * @param self         a Map
5344      * @param initialValue some initial value
5345      * @param closure      a 2 or 3 arg Closure
5346      * @return the result of the last closure call
5347      * @since 1.8.1
5348      */
5349     public static <K, V, T, U extends T, W extends T> T inject(Map<K, V> self, U initialValue, @ClosureParams(value=FromString.class,options={"U,Map.Entry<K,V>","U,K,V"})  Closure<W> closure) {
5350         T value = initialValue;
5351         for (Map.Entry<K, V> entry : self.entrySet()) {
5352             if (closure.getMaximumNumberOfParameters() == 3) {
5353                 value = closure.call(value, entry.getKey(), entry.getValue());
5354             } else {
5355                 value = closure.call(value, entry);
5356             }
5357         }
5358         return value;
5359     }
5360 
5361 
5362     /**
5363      * Iterates through the given Iterator, passing in the initial value to
5364      * the closure along with the first item. The result is passed back (injected) into
5365      * the closure along with the second item. The new result is injected back into
5366      * the closure along with the third item and so on until the Iterator has been
5367      * expired of values. Also known as foldLeft in functional parlance.
5368      *
5369      * @param self         an Iterator
5370      * @param initialValue some initial value
5371      * @param closure      a closure
5372      * @return the result of the last closure call
5373      * @see #inject(Collection, Object, Closure)
5374      * @since 1.5.0
5375      */
5376     public static <E,T, U extends T, V extends T> T inject(Iterator<E> self, U initialValue, @ClosureParams(value=FromString.class,options="U,E") Closure<V> closure) {
5377         T value = initialValue;
5378         Object[] params = new Object[2];
5379         while (self.hasNext()) {
5380             Object item = self.next();
5381             params[0] = value;
5382             params[1] = item;
5383             value = closure.call(params);
5384         }
5385         return value;
5386     }
5387 
5388     /**
5389      * Iterates through the given Object, passing in the first value to
5390      * the closure along with the first item. The result is passed back (injected) into
5391      * the closure along with the second item. The new result is injected back into
5392      * the closure along with the third item and so on until further iteration of
5393      * the object is not possible. Also known as foldLeft in functional parlance.
5394      *
5395      * @param self         an Object
5396      * @param closure      a closure
5397      * @return the result of the last closure call
5398      * @throws NoSuchElementException if the collection is empty.
5399      * @see #inject(Collection, Object, Closure)
5400      * @since 1.8.7
5401      */
5402     public static <T, V extends T> T inject(Object self, Closure<V> closure) {
5403         Iterator iter = InvokerHelper.asIterator(self);
5404         if( !iter.hasNext() ) {
5405             throw new NoSuchElementException( "Cannot call inject() over an empty iterable without passing an initial value." ) ;
5406         }
5407         Object initialValue = iter.next() ;
5408         return (T) inject(iter, initialValue, closure);
5409     }
5410 
5411     /**
5412      * Iterates through the given Object, passing in the initial value to
5413      * the closure along with the first item. The result is passed back (injected) into
5414      * the closure along with the second item. The new result is injected back into
5415      * the closure along with the third item and so on until further iteration of
5416      * the object is not possible. Also known as foldLeft in functional parlance.
5417      *
5418      * @param self         an Object
5419      * @param initialValue some initial value
5420      * @param closure      a closure
5421      * @return the result of the last closure call
5422      * @see #inject(Collection, Object, Closure)
5423      * @since 1.5.0
5424      */
5425     public static <T, U extends T, V extends T> T inject(Object self, U initialValue, Closure<V> closure) {
5426         Iterator iter = InvokerHelper.asIterator(self);
5427         return (T) inject(iter, initialValue, closure);
5428     }
5429 
5430     /**
5431      * Iterates through the given array as with inject(Object[],initialValue,closure), but
5432      * using the first element of the array as the initialValue, and then iterating
5433      * the remaining elements of the array.
5434      *
5435      * @param self         an Object[]
5436      * @param closure      a closure
5437      * @return the result of the last closure call
5438      * @throws NoSuchElementException if the array is empty.
5439      * @see #inject(Object[], Object, Closure)
5440      * @since 1.8.7
5441      */
5442     public static <E,T, V extends T> T inject(E[] self, @ClosureParams(value=FromString.class,options="E,E") Closure<V> closure) {
5443         return inject( (Object)self, closure ) ;
5444     }
5445 
5446     /**
5447      * Iterates through the given array, passing in the initial value to
5448      * the closure along with the first item. The result is passed back (injected) into
5449      * the closure along with the second item. The new result is injected back into
5450      * the closure along with the third item and so on until all elements of the array
5451      * have been used. Also known as foldLeft in functional parlance.
5452      *
5453      * @param self         an Object[]
5454      * @param initialValue some initial value
5455      * @param closure      a closure
5456      * @return the result of the last closure call
5457      * @see #inject(Collection, Object, Closure)
5458      * @since 1.5.0
5459      */
5460     public static <E, T, U extends T, V extends T> T inject(E[] self, U initialValue, @ClosureParams(value=FromString.class,options="U,E") Closure<V> closure) {
5461         Object[] params = new Object[2];
5462         T value = initialValue;
5463         for (Object next : self) {
5464             params[0] = value;
5465             params[1] = next;
5466             value = closure.call(params);
5467         }
5468         return value;
5469     }
5470 
5471     /**
5472      * @deprecated Use the Iterable version of sum instead
5473      * @see #sum(Iterable)
5474      * @since 1.0
5475      */
5476     @Deprecated
5477     public static Object sum(Collection self) {
5478         return sum((Iterable)self);
5479     }
5480 
5481     /**
5482      * Sums the items in an Iterable.  This is equivalent to invoking the
5483      * "plus" method on all items in the Iterable.
5484      * <pre class="groovyTestCase">assert 1+2+3+4 == [1,2,3,4].sum()</pre>
5485      *
5486      * @param self Collection of values to add together
5487      * @return The sum of all of the items
5488      * @since 2.2.0
5489      */
5490     public static Object sum(Iterable self) {
5491         return sum(self, null, true);
5492     }
5493 
5494     /**
5495      * Sums the items in an array.  This is equivalent to invoking the
5496      * "plus" method on all items in the array.
5497      *
5498      * @param self The array of values to add together
5499      * @return The sum of all of the items
5500      * @see #sum(java.util.Collection)
5501      * @since 1.7.1
5502      */
5503     public static Object sum(Object[] self) {
5504         return sum(toList(self), null, true);
5505     }
5506 
5507     /**
5508      * Sums the items from an Iterator.  This is equivalent to invoking the
5509      * "plus" method on all items from the Iterator. The iterator will become
5510      * exhausted of elements after determining the sum value.
5511      *
5512      * @param self an Iterator for the values to add together
5513      * @return The sum of all of the items
5514      * @since 1.5.5
5515      */
5516     public static Object sum(Iterator<Object> self) {
5517         return sum(toList(self), null, true);
5518     }
5519 
5520     /**
5521      * Sums the items in an array.
5522      * <pre class="groovyTestCase">assert (1+2+3+4 as byte) == ([1,2,3,4] as byte[]).sum()</pre>
5523      *
5524      * @param self The array of values to add together
5525      * @return The sum of all of the items
5526      * @since 2.4.2
5527      */
5528     public static byte sum(byte[] self) {
5529         return sum(self, (byte) 0);
5530     }
5531 
5532     /**
5533      * Sums the items in an array.
5534      * <pre class="groovyTestCase">assert (1+2+3+4 as short) == ([1,2,3,4] as short[]).sum()</pre>
5535      *
5536      * @param self The array of values to add together
5537      * @return The sum of all of the items
5538      * @since 2.4.2
5539      */
5540     public static short sum(short[] self) {
5541         return sum(self, (short) 0);
5542     }
5543 
5544     /**
5545      * Sums the items in an array.
5546      * <pre class="groovyTestCase">assert 1+2+3+4 == ([1,2,3,4] as int[]).sum()</pre>
5547      *
5548      * @param self The array of values to add together
5549      * @return The sum of all of the items
5550      * @since 2.4.2
5551      */
5552     public static int sum(int[] self) {
5553         return sum(self, 0);
5554     }
5555 
5556     /**
5557      * Sums the items in an array.
5558      * <pre class="groovyTestCase">assert (1+2+3+4 as long) == ([1,2,3,4] as long[]).sum()</pre>
5559      *
5560      * @param self The array of values to add together
5561      * @return The sum of all of the items
5562      * @since 2.4.2
5563      */
5564     public static long sum(long[] self) {
5565         return sum(self, (long) 0);
5566     }
5567 
5568     /**
5569      * Sums the items in an array.
5570      * <pre class="groovyTestCase">assert (1+2+3+4 as char) == ([1,2,3,4] as char[]).sum()</pre>
5571      *
5572      * @param self The array of values to add together
5573      * @return The sum of all of the items
5574      * @since 2.4.2
5575      */
5576     public static char sum(char[] self) {
5577         return sum(self, (char) 0);
5578     }
5579 
5580     /**
5581      * Sums the items in an array.
5582      * <pre class="groovyTestCase">assert (1+2+3+4 as float) == ([1,2,3,4] as float[]).sum()</pre>
5583      *
5584      * @param self The array of values to add together
5585      * @return The sum of all of the items
5586      * @since 2.4.2
5587      */
5588     public static float sum(float[] self) {
5589         return sum(self, (float) 0);
5590     }
5591 
5592     /**
5593      * Sums the items in an array.
5594      * <pre class="groovyTestCase">assert (1+2+3+4 as double) == ([1,2,3,4] as double[]).sum()</pre>
5595      *
5596      * @param self The array of values to add together
5597      * @return The sum of all of the items
5598      * @since 2.4.2
5599      */
5600     public static double sum(double[] self) {
5601         return sum(self, (double) 0);
5602     }
5603 
5604     /**
5605      * @deprecated Use the Iterable version of sum instead
5606      * @see #sum(Iterable, Object)
5607      * @since 1.5.0
5608      */
5609     @Deprecated
5610     public static Object sum(Collection self, Object initialValue) {
5611         return sum(self, initialValue, false);
5612     }
5613 
5614     /**
5615      * Sums the items in an Iterable, adding the result to some initial value.
5616      * <pre class="groovyTestCase">
5617      * assert 5+1+2+3+4 == [1,2,3,4].sum(5)
5618      * </pre>
5619      *
5620      * @param self         an Iterable of values to sum
5621      * @param initialValue the items in the collection will be summed to this initial value
5622      * @return The sum of all of the items.
5623      * @since 2.2.0
5624      */
5625     public static Object sum(Iterable self, Object initialValue) {
5626         return sum(self, initialValue, false);
5627     }
5628 
5629     /**
5630      * Sums the items in an array, adding the result to some initial value.
5631      *
5632      * @param self         an array of values to sum
5633      * @param initialValue the items in the array will be summed to this initial value
5634      * @return The sum of all of the items.
5635      * @since 1.7.1
5636      */
5637     public static Object sum(Object[] self, Object initialValue) {
5638         return sum(toList(self), initialValue, false);
5639     }
5640 
5641     /**
5642      * Sums the items from an Iterator, adding the result to some initial value.  This is
5643      * equivalent to invoking the "plus" method on all items from the Iterator. The iterator
5644      * will become exhausted of elements after determining the sum value.
5645      *
5646      * @param self         an Iterator for the values to add together
5647      * @param initialValue the items in the collection will be summed to this initial value
5648      * @return The sum of all of the items
5649      * @since 1.5.5
5650      */
5651     public static Object sum(Iterator<Object> self, Object initialValue) {
5652         return sum(toList(self), initialValue, false);
5653     }
5654 
5655     private static Object sum(Iterable self, Object initialValue, boolean first) {
5656         Object result = initialValue;
5657         Object[] param = new Object[1];
5658         for (Object next : self) {
5659             param[0] = next;
5660             if (first) {
5661                 result = param[0];
5662                 first = false;
5663                 continue;
5664             }
5665             MetaClass metaClass = InvokerHelper.getMetaClass(result);
5666             result = metaClass.invokeMethod(result, "plus", param);
5667         }
5668         return result;
5669     }
5670 
5671     /**
5672      * Sums the items in an array, adding the result to some initial value.
5673      * <pre class="groovyTestCase">assert (5+1+2+3+4 as byte) == ([1,2,3,4] as byte[]).sum(5)</pre>
5674      *
5675      * @param self         an array of values to sum
5676      * @param initialValue the items in the array will be summed to this initial value
5677      * @return The sum of all of the items.
5678      * @since 2.4.2
5679      */
5680     public static byte sum(byte[] self, byte initialValue) {
5681         byte s = initialValue;
5682         for (byte v : self) {
5683             s += v;
5684         }
5685         return s;
5686     }
5687 
5688     /**
5689      * Sums the items in an array, adding the result to some initial value.
5690      * <pre class="groovyTestCase">assert (5+1+2+3+4 as short) == ([1,2,3,4] as short[]).sum(5)</pre>
5691      *
5692      * @param self         an array of values to sum
5693      * @param initialValue the items in the array will be summed to this initial value
5694      * @return The sum of all of the items.
5695      * @since 2.4.2
5696      */
5697     public static short sum(short[] self, short initialValue) {
5698         short s = initialValue;
5699         for (short v : self) {
5700             s += v;
5701         }
5702         return s;
5703     }
5704 
5705     /**
5706      * Sums the items in an array, adding the result to some initial value.
5707      * <pre class="groovyTestCase">assert 5+1+2+3+4 == ([1,2,3,4] as int[]).sum(5)</pre>
5708      *
5709      * @param self         an array of values to sum
5710      * @param initialValue the items in the array will be summed to this initial value
5711      * @return The sum of all of the items.
5712      * @since 2.4.2
5713      */
5714     public static int sum(int[] self, int initialValue) {
5715         int s = initialValue;
5716         for (int v : self) {
5717             s += v;
5718         }
5719         return s;
5720     }
5721 
5722     /**
5723      * Sums the items in an array, adding the result to some initial value.
5724      * <pre class="groovyTestCase">assert (5+1+2+3+4 as long) == ([1,2,3,4] as long[]).sum(5)</pre>
5725      *
5726      * @param self         an array of values to sum
5727      * @param initialValue the items in the array will be summed to this initial value
5728      * @return The sum of all of the items.
5729      * @since 2.4.2
5730      */
5731     public static long sum(long[] self, long initialValue) {
5732         long s = initialValue;
5733         for (long v : self) {
5734             s += v;
5735         }
5736         return s;
5737     }
5738 
5739     /**
5740      * Sums the items in an array, adding the result to some initial value.
5741      * <pre class="groovyTestCase">assert (5+1+2+3+4 as char) == ([1,2,3,4] as char[]).sum(5)</pre>
5742      *
5743      * @param self         an array of values to sum
5744      * @param initialValue the items in the array will be summed to this initial value
5745      * @return The sum of all of the items.
5746      * @since 2.4.2
5747      */
5748     public static char sum(char[] self, char initialValue) {
5749         char s = initialValue;
5750         for (char v : self) {
5751             s += v;
5752         }
5753         return s;
5754     }
5755 
5756     /**
5757      * Sums the items in an array, adding the result to some initial value.
5758      * <pre class="groovyTestCase">assert (5+1+2+3+4 as float) == ([1,2,3,4] as float[]).sum(5)</pre>
5759      *
5760      * @param self         an array of values to sum
5761      * @param initialValue the items in the array will be summed to this initial value
5762      * @return The sum of all of the items.
5763      * @since 2.4.2
5764      */
5765     public static float sum(float[] self, float initialValue) {
5766         float s = initialValue;
5767         for (float v : self) {
5768             s += v;
5769         }
5770         return s;
5771     }
5772 
5773     /**
5774      * Sums the items in an array, adding the result to some initial value.
5775      * <pre class="groovyTestCase">assert (5+1+2+3+4 as double) == ([1,2,3,4] as double[]).sum(5)</pre>
5776      *
5777      * @param self         an array of values to sum
5778      * @param initialValue the items in the array will be summed to this initial value
5779      * @return The sum of all of the items.
5780      * @since 2.4.2
5781      */
5782     public static double sum(double[] self, double initialValue) {
5783         double s = initialValue;
5784         for (double v : self) {
5785             s += v;
5786         }
5787         return s;
5788     }
5789 
5790     /**
5791      * @deprecated Use the Iterable version of sum instead
5792      * @see #sum(Iterable, Closure)
5793      * @since 1.0
5794      */
5795     @Deprecated
5796     public static Object sum(Collection self, Closure closure) {
5797         return sum((Iterable)self, closure);
5798     }
5799 
5800     /**
5801      * Sums the result of apply a closure to each item of an Iterable.
5802      * <code>coll.sum(closure)</code> is equivalent to:
5803      * <code>coll.collect(closure).sum()</code>.
5804      * <pre class="groovyTestCase">assert 4+6+10+12 == [2,3,5,6].sum { it * 2 }</pre>
5805      *
5806      * @param self    an Iterable
5807      * @param closure a single parameter closure that returns a numeric value.
5808      * @return The sum of the values returned by applying the closure to each
5809      *         item of the Iterable.
5810      * @since 2.2.0
5811      */
5812     public static Object sum(Iterable self, Closure closure) {
5813         return sum(self, null, closure, true);
5814     }
5815 
5816     /**
5817      * Sums the result of apply a closure to each item of an array.
5818      * <code>array.sum(closure)</code> is equivalent to:
5819      * <code>array.collect(closure).sum()</code>.
5820      *
5821      * @param self    An array
5822      * @param closure a single parameter closure that returns a numeric value.
5823      * @return The sum of the values returned by applying the closure to each
5824      *         item of the array.
5825      * @since 1.7.1
5826      */
5827     public static Object sum(Object[] self, Closure closure) {
5828         return sum(toList(self), null, closure, true);
5829     }
5830 
5831     /**
5832      * Sums the result of apply a closure to each item returned from an iterator.
5833      * <code>iter.sum(closure)</code> is equivalent to:
5834      * <code>iter.collect(closure).sum()</code>. The iterator will become
5835      * exhausted of elements after determining the sum value.
5836      *
5837      * @param self    An Iterator
5838      * @param closure a single parameter closure that returns a numeric value.
5839      * @return The sum of the values returned by applying the closure to each
5840      *         item from the Iterator.
5841      * @since 1.7.1
5842      */
5843     public static Object sum(Iterator<Object> self, Closure closure) {
5844         return sum(toList(self), null, closure, true);
5845     }
5846 
5847     /**
5848      * @deprecated Use the Iterable version of sum instead
5849      * @see #sum(Iterable, Object, Closure)
5850      * @since 1.5.0
5851      */
5852     @Deprecated
5853     public static Object sum(Collection self, Object initialValue, Closure closure) {
5854         return sum((Iterable)self, initialValue, closure);
5855     }
5856 
5857     /**
5858      * Sums the result of applying a closure to each item of an Iterable to some initial value.
5859      * <code>coll.sum(initVal, closure)</code> is equivalent to:
5860      * <code>coll.collect(closure).sum(initVal)</code>.
5861      * <pre class="groovyTestCase">assert 50+4+6+10+12 == [2,3,5,6].sum(50) { it * 2 }</pre>
5862      *
5863      * @param self         an Iterable
5864      * @param closure      a single parameter closure that returns a numeric value.
5865      * @param initialValue the closure results will be summed to this initial value
5866      * @return The sum of the values returned by applying the closure to each
5867      *         item of the collection.
5868      * @since 1.5.0
5869      */
5870     public static Object sum(Iterable self, Object initialValue, Closure closure) {
5871         return sum(self, initialValue, closure, false);
5872     }
5873 
5874     /**
5875      * Sums the result of applying a closure to each item of an array to some initial value.
5876      * <code>array.sum(initVal, closure)</code> is equivalent to:
5877      * <code>array.collect(closure).sum(initVal)</code>.
5878      *
5879      * @param self         an array
5880      * @param closure      a single parameter closure that returns a numeric value.
5881      * @param initialValue the closure results will be summed to this initial value
5882      * @return The sum of the values returned by applying the closure to each
5883      *         item of the array.
5884      * @since 1.7.1
5885      */
5886     public static Object sum(Object[] self, Object initialValue, Closure closure) {
5887         return sum(toList(self), initialValue, closure, false);
5888     }
5889 
5890     /**
5891      * Sums the result of applying a closure to each item of an Iterator to some initial value.
5892      * <code>iter.sum(initVal, closure)</code> is equivalent to:
5893      * <code>iter.collect(closure).sum(initVal)</code>. The iterator will become
5894      * exhausted of elements after determining the sum value.
5895      *
5896      * @param self         an Iterator
5897      * @param closure      a single parameter closure that returns a numeric value.
5898      * @param initialValue the closure results will be summed to this initial value
5899      * @return The sum of the values returned by applying the closure to each
5900      *         item from the Iterator.
5901      * @since 1.7.1
5902      */
5903     public static Object sum(Iterator<Object> self, Object initialValue, Closure closure) {
5904         return sum(toList(self), initialValue, closure, false);
5905     }
5906 
5907     private static Object sum(Iterable self, Object initialValue, Closure closure, boolean first) {
5908         Object result = initialValue;
5909         Object[] closureParam = new Object[1];
5910         Object[] plusParam = new Object[1];
5911         for (Object next : self) {
5912             closureParam[0] = next;
5913             plusParam[0] = closure.call(closureParam);
5914             if (first) {
5915                 result = plusParam[0];
5916                 first = false;
5917                 continue;
5918             }
5919             MetaClass metaClass = InvokerHelper.getMetaClass(result);
5920             result = metaClass.invokeMethod(result, "plus", plusParam);
5921         }
5922         return result;
5923     }
5924 
5925     /**
5926      * Concatenates the <code>toString()</code> representation of each
5927      * item from the iterator, with the given String as a separator between
5928      * each item. The iterator will become exhausted of elements after
5929      * determining the resulting conjoined value.
5930      *
5931      * @param self      an Iterator of items
5932      * @param separator a String separator
5933      * @return the joined String
5934      * @since 1.5.5
5935      */
5936     public static String join(Iterator<Object> self, String separator) {
5937         return join((Iterable)toList(self), separator);
5938     }
5939 
5940     /**
5941      * @deprecated Use the Iterable version of join instead
5942      * @see #join(Iterable, String)
5943      * @since 1.0
5944      */
5945     @Deprecated
5946     public static String join(Collection self, String separator) {
5947         return join((Iterable)self, separator);
5948     }
5949 
5950     /**
5951      * Concatenates the <code>toString()</code> representation of each
5952      * item in this Iterable, with the given String as a separator between each item.
5953      * <pre class="groovyTestCase">assert "1, 2, 3" == [1,2,3].join(", ")</pre>
5954      *
5955      * @param self      an Iterable of objects
5956      * @param separator a String separator
5957      * @return the joined String
5958      * @since 1.0
5959      */
5960     public static String join(Iterable self, String separator) {
5961         StringBuilder buffer = new StringBuilder();
5962         boolean first = true;
5963 
5964         if (separator == null) separator = "";
5965 
5966         for (Object value : self) {
5967             if (first) {
5968                 first = false;
5969             } else {
5970                 buffer.append(separator);
5971             }
5972             buffer.append(InvokerHelper.toString(value));
5973         }
5974         return buffer.toString();
5975     }
5976 
5977     /**
5978      * Concatenates the <code>toString()</code> representation of each
5979      * items in this array, with the given String as a separator between each
5980      * item.
5981      *
5982      * @param self      an array of Object
5983      * @param separator a String separator
5984      * @return the joined String
5985      * @since 1.0
5986      */
5987     public static String join(Object[] self, String separator) {
5988         StringBuilder buffer = new StringBuilder();
5989         boolean first = true;
5990 
5991         if (separator == null) separator = "";
5992 
5993         for (Object next : self) {
5994             String value = InvokerHelper.toString(next);
5995             if (first) {
5996                 first = false;
5997             } else {
5998                 buffer.append(separator);
5999             }
6000             buffer.append(value);
6001         }
6002         return buffer.toString();
6003     }
6004 
6005     /**
6006      * Concatenates the string representation of each
6007      * items in this array, with the given String as a separator between each
6008      * item.
6009      *
6010      * @param self      an array of boolean
6011      * @param separator a String separator
6012      * @return the joined String
6013      * @since 2.4.1
6014      */
6015     public static String join(boolean[] self, String separator) {
6016         StringBuilder buffer = new StringBuilder();
6017         boolean first = true;
6018 
6019         if (separator == null) separator = "";
6020 
6021         for (boolean next : self) {
6022             if (first) {
6023                 first = false;
6024             } else {
6025                 buffer.append(separator);
6026             }
6027             buffer.append(next);
6028         }
6029         return buffer.toString();
6030     }
6031 
6032     /**
6033      * Concatenates the string representation of each
6034      * items in this array, with the given String as a separator between each
6035      * item.
6036      *
6037      * @param self      an array of byte
6038      * @param separator a String separator
6039      * @return the joined String
6040      * @since 2.4.1
6041      */
6042     public static String join(byte[] self, String separator) {
6043         StringBuilder buffer = new StringBuilder();
6044         boolean first = true;
6045 
6046         if (separator == null) separator = "";
6047 
6048         for (byte next : self) {
6049             if (first) {
6050                 first = false;
6051             } else {
6052                 buffer.append(separator);
6053             }
6054             buffer.append(next);
6055         }
6056         return buffer.toString();
6057     }
6058 
6059     /**
6060      * Concatenates the string representation of each
6061      * items in this array, with the given String as a separator between each
6062      * item.
6063      *
6064      * @param self      an array of char
6065      * @param separator a String separator
6066      * @return the joined String
6067      * @since 2.4.1
6068      */
6069     public static String join(char[] self, String separator) {
6070         StringBuilder buffer = new StringBuilder();
6071         boolean first = true;
6072 
6073         if (separator == null) separator = "";
6074 
6075         for (char next : self) {
6076             if (first) {
6077                 first = false;
6078             } else {
6079                 buffer.append(separator);
6080             }
6081             buffer.append(next);
6082         }
6083         return buffer.toString();
6084     }
6085 
6086     /**
6087      * Concatenates the string representation of each
6088      * items in this array, with the given String as a separator between each
6089      * item.
6090      *
6091      * @param self      an array of double
6092      * @param separator a String separator
6093      * @return the joined String
6094      * @since 2.4.1
6095      */
6096     public static String join(double[] self, String separator) {
6097         StringBuilder buffer = new StringBuilder();
6098         boolean first = true;
6099 
6100         if (separator == null) separator = "";
6101 
6102         for (double next : self) {
6103             if (first) {
6104                 first = false;
6105             } else {
6106                 buffer.append(separator);
6107             }
6108             buffer.append(next);
6109         }
6110         return buffer.toString();
6111     }
6112 
6113     /**
6114      * Concatenates the string representation of each
6115      * items in this array, with the given String as a separator between each
6116      * item.
6117      *
6118      * @param self      an array of float
6119      * @param separator a String separator
6120      * @return the joined String
6121      * @since 2.4.1
6122      */
6123     public static String join(float[] self, String separator) {
6124         StringBuilder buffer = new StringBuilder();
6125         boolean first = true;
6126 
6127         if (separator == null) separator = "";
6128 
6129         for (float next : self) {
6130             if (first) {
6131                 first = false;
6132             } else {
6133                 buffer.append(separator);
6134             }
6135             buffer.append(next);
6136         }
6137         return buffer.toString();
6138     }
6139 
6140     /**
6141      * Concatenates the string representation of each
6142      * items in this array, with the given String as a separator between each
6143      * item.
6144      *
6145      * @param self      an array of int
6146      * @param separator a String separator
6147      * @return the joined String
6148      * @since 2.4.1
6149      */
6150     public static String join(int[] self, String separator) {
6151         StringBuilder buffer = new StringBuilder();
6152         boolean first = true;
6153 
6154         if (separator == null) separator = "";
6155 
6156         for (int next : self) {
6157             if (first) {
6158                 first = false;
6159             } else {
6160                 buffer.append(separator);
6161             }
6162             buffer.append(next);
6163         }
6164         return buffer.toString();
6165     }
6166 
6167     /**
6168      * Concatenates the string representation of each
6169      * items in this array, with the given String as a separator between each
6170      * item.
6171      *
6172      * @param self      an array of long
6173      * @param separator a String separator
6174      * @return the joined String
6175      * @since 2.4.1
6176      */
6177     public static String join(long[] self, String separator) {
6178         StringBuilder buffer = new StringBuilder();
6179         boolean first = true;
6180 
6181         if (separator == null) separator = "";
6182 
6183         for (long next : self) {
6184             if (first) {
6185                 first = false;
6186             } else {
6187                 buffer.append(separator);
6188             }
6189             buffer.append(next);
6190         }
6191         return buffer.toString();
6192     }
6193 
6194     /**
6195      * Concatenates the string representation of each
6196      * items in this array, with the given String as a separator between each
6197      * item.
6198      *
6199      * @param self      an array of short
6200      * @param separator a String separator
6201      * @return the joined String
6202      * @since 2.4.1
6203      */
6204     public static String join(short[] self, String separator) {
6205         StringBuilder buffer = new StringBuilder();
6206         boolean first = true;
6207 
6208         if (separator == null) separator = "";
6209 
6210         for (short next : self) {
6211             if (first) {
6212                 first = false;
6213             } else {
6214                 buffer.append(separator);
6215             }
6216             buffer.append(next);
6217         }
6218         return buffer.toString();
6219     }
6220 
6221     /**
6222      * @deprecated Use the Iterable version of min instead
6223      * @see #min(Iterable)
6224      * @since 1.0
6225      */
6226     @Deprecated 
6227     public static <T> T min(Collection<T> self) {
6228         return GroovyCollections.min(self);
6229     }
6230 
6231     /**
6232      * Adds min() method to Collection objects.
6233      * <pre class="groovyTestCase">assert 2 == [4,2,5].min()</pre>
6234      *
6235      * @param self a Collection
6236      * @return the minimum value
6237      * @see groovy.util.GroovyCollections#min(java.util.Collection)
6238      * @since 1.0
6239      */
6240     public static <T> T min(Iterable<T> self) {
6241         return GroovyCollections.min(self);
6242     }
6243 
6244     /**
6245      * Adds min() method to Iterator objects. The iterator will become
6246      * exhausted of elements after determining the minimum value.
6247      *
6248      * @param self an Iterator
6249      * @return the minimum value
6250      * @see #min(java.util.Collection)
6251      * @since 1.5.5
6252      */
6253     public static <T> T min(Iterator<T> self) {
6254         return min((Iterable<T>)toList(self));
6255     }
6256 
6257     /**
6258      * Adds min() method to Object arrays.
6259      *
6260      * @param self an array
6261      * @return the minimum value
6262      * @see #min(java.util.Collection)
6263      * @since 1.5.5
6264      */
6265     public static <T> T min(T[] self) {
6266         return min((Iterable<T>)toList(self));
6267     }
6268 
6269     /**
6270      * @deprecated Use the Iterable version of min instead
6271      * @see #min(Iterable, Comparator)
6272      * @since 1.0
6273      */
6274     @Deprecated
6275     public static <T> T min(Collection<T> self, Comparator<T> comparator) {
6276         return min((Iterable<T>) self, comparator);
6277     }
6278 
6279     /**
6280      * Selects the minimum value found in the Iterable using the given comparator.
6281      * <pre class="groovyTestCase">assert "hi" == ["hello","hi","hey"].min( { a, b -> a.length() <=> b.length() } as Comparator )</pre>
6282      *
6283      * @param self       an Iterable
6284      * @param comparator a Comparator
6285      * @return the minimum value or null for an empty Iterable
6286      * @since 2.2.0
6287      */
6288     public static <T> T min(Iterable<T> self, Comparator<T> comparator) {
6289         T answer = null;
6290         boolean first = true;
6291         for (T value : self) {
6292             if (first) {
6293                 first = false;
6294                 answer = value;
6295             } else if (comparator.compare(value, answer) < 0) {
6296                 answer = value;
6297             }
6298         }
6299         return answer;
6300     }
6301 
6302     /**
6303      * Selects the minimum value found from the Iterator using the given comparator.
6304      *
6305      * @param self       an Iterator
6306      * @param comparator a Comparator
6307      * @return the minimum value
6308      * @see #min(java.util.Collection, java.util.Comparator)
6309      * @since 1.5.5
6310      */
6311     public static <T> T min(Iterator<T> self, Comparator<T> comparator) {
6312         return min((Iterable<T>)toList(self), comparator);
6313     }
6314 
6315     /**
6316      * Selects the minimum value found from the Object array using the given comparator.
6317      *
6318      * @param self       an array
6319      * @param comparator a Comparator
6320      * @return the minimum value
6321      * @see #min(java.util.Collection, java.util.Comparator)
6322      * @since 1.5.5
6323      */
6324     public static <T> T min(T[] self, Comparator<T> comparator) {
6325         return min((Iterable<T>)toList(self), comparator);
6326     }
6327 
6328     /**
6329      * @deprecated Use the Iterable version of min instead
6330      * @see #min(Iterable, Closure)
6331      * @since 1.0
6332      */
6333     @Deprecated
6334     public static <T> T min(Collection<T> self, Closure closure) {
6335         return min((Iterable<T>)self, closure);
6336     }
6337 
6338     /**
6339      * Selects the item in the iterable which when passed as a parameter to the supplied closure returns the
6340      * minimum value. A null return value represents the least possible return value. If more than one item
6341      * has the minimum value, an arbitrary choice is made between the items having the minimum value.
6342      * <p>
6343      * If the closure has two parameters
6344      * it is used like a traditional Comparator. I.e. it should compare
6345      * its two parameters for order, returning a negative integer,
6346      * zero, or a positive integer when the first parameter is less than,
6347      * equal to, or greater than the second respectively. Otherwise,
6348      * the Closure is assumed to take a single parameter and return a
6349      * Comparable (typically an Integer) which is then used for
6350      * further comparison.
6351      * <pre class="groovyTestCase">
6352      * assert "hi" == ["hello","hi","hey"].min { it.length() }
6353      * </pre>
6354      * <pre class="groovyTestCase">
6355      * def lastDigit = { a, b -> a % 10 <=> b % 10 }
6356      * assert [19, 55, 91].min(lastDigit) == 91
6357      * </pre>
6358      * <pre class="groovyTestCase">
6359      * def pets = ['dog', 'cat', 'anaconda']
6360      * def shortestName = pets.min{ it.size() } // one of 'dog' or 'cat'
6361      * assert shortestName.size() == 3
6362      * </pre>
6363      *
6364      * @param self    an Iterable
6365      * @param closure a 1 or 2 arg Closure used to determine the correct ordering
6366      * @return an item from the Iterable having the minimum value returned by calling the supplied closure with that item as parameter or null for an empty Iterable
6367      * @since 1.0
6368      */
6369     public static <T> T min(Iterable<T> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure closure) {
6370         int params = closure.getMaximumNumberOfParameters();
6371         if (params != 1) {
6372             return min(self, new ClosureComparator<T>(closure));
6373         }
6374         boolean first = true;
6375         T answer = null;
6376         Object answerValue = null;
6377         for (T item : self) {
6378             Object value = closure.call(item);
6379             if (first) {
6380                 first = false;
6381                 answer = item;
6382                 answerValue = value;
6383             } else if (ScriptBytecodeAdapter.compareLessThan(value, answerValue)) {
6384                 answer = item;
6385                 answerValue = value;
6386             }
6387         }
6388         return answer;
6389     }
6390 
6391     /**
6392      * Selects an entry in the map having the minimum
6393      * calculated value as determined by the supplied closure.
6394      * If more than one entry has the minimum value,
6395      * an arbitrary choice is made between the entries having the minimum value.
6396      * <p>
6397      * If the closure has two parameters
6398      * it is used like a traditional Comparator. I.e. it should compare
6399      * its two parameters for order, returning a negative integer,
6400      * zero, or a positive integer when the first parameter is less than,
6401      * equal to, or greater than the second respectively. Otherwise,
6402      * the Closure is assumed to take a single parameter and return a
6403      * Comparable (typically an Integer) which is then used for
6404      * further comparison.
6405      * <pre class="groovyTestCase">
6406      * def zoo = [monkeys:6, lions:5, tigers:7]
6407      * def leastCommonEntry = zoo.min{ it.value }
6408      * assert leastCommonEntry.value == 5
6409      * def mostCommonEntry = zoo.min{ a, b -> b.value <=> a.value } // double negative!
6410      * assert mostCommonEntry.value == 7
6411      * </pre>
6412      * Edge case for multiple min values:
6413      * <pre class="groovyTestCase">
6414      * def zoo = [monkeys:6, lions:5, tigers:7]
6415      * def lastCharOfName = { e -> e.key[-1] }
6416      * def ans = zoo.min(lastCharOfName) // some random entry
6417      * assert lastCharOfName(ans) == 's'
6418      * </pre>
6419      *
6420      * @param self    a Map
6421      * @param closure a 1 or 2 arg Closure used to determine the correct ordering
6422      * @return the Map.Entry having the minimum value as determined by the closure
6423      * @since 1.7.6
6424      */
6425     public static <K, V> Map.Entry<K, V> min(Map<K, V> self, @ClosureParams(value=FromString.class, options={"Map.Entry<K,V>", "Map.Entry<K,V>,Map.Entry<K,V>"}) Closure closure) {
6426         return min((Iterable<Map.Entry<K, V>>)self.entrySet(), closure);
6427     }
6428 
6429     /**
6430      * Selects an entry in the map having the maximum
6431      * calculated value as determined by the supplied closure.
6432      * If more than one entry has the maximum value,
6433      * an arbitrary choice is made between the entries having the maximum value.
6434      * <p>
6435      * If the closure has two parameters
6436      * it is used like a traditional Comparator. I.e. it should compare
6437      * its two parameters for order, returning a negative integer,
6438      * zero, or a positive integer when the first parameter is less than,
6439      * equal to, or greater than the second respectively. Otherwise,
6440      * the Closure is assumed to take a single parameter and return a
6441      * Comparable (typically an Integer) which is then used for
6442      * further comparison. An example:
6443      * <pre class="groovyTestCase">
6444      * def zoo = [monkeys:6, lions:5, tigers:7]
6445      * def mostCommonEntry = zoo.max{ it.value }
6446      * assert mostCommonEntry.value == 7
6447      * def leastCommonEntry = zoo.max{ a, b -> b.value <=> a.value } // double negative!
6448      * assert leastCommonEntry.value == 5
6449      * </pre>
6450      * Edge case for multiple max values:
6451      * <pre class="groovyTestCase">
6452      * def zoo = [monkeys:6, lions:5, tigers:7]
6453      * def lengthOfNamePlusNumber = { e -> e.key.size() + e.value }
6454      * def ans = zoo.max(lengthOfNamePlusNumber) // one of [monkeys:6, tigers:7]
6455      * assert lengthOfNamePlusNumber(ans) == 13
6456      * </pre>
6457      *
6458      * @param self    a Map
6459      * @param closure a 1 or 2 arg Closure used to determine the correct ordering
6460      * @return the Map.Entry having the maximum value as determined by the closure
6461      * @since 1.7.6
6462      */
6463     public static <K, V> Map.Entry<K, V> max(Map<K, V> self, @ClosureParams(value=FromString.class, options={"Map.Entry<K,V>", "Map.Entry<K,V>,Map.Entry<K,V>"}) Closure closure) {
6464         return max((Iterable<Map.Entry<K, V>>)self.entrySet(), closure);
6465     }
6466 
6467     /**
6468      * Selects the minimum value found from the Iterator
6469      * using the closure to determine the correct ordering.
6470      * The iterator will become
6471      * exhausted of elements after this operation.
6472      * <p>
6473      * If the closure has two parameters
6474      * it is used like a traditional Comparator. I.e. it should compare
6475      * its two parameters for order, returning a negative integer,
6476      * zero, or a positive integer when the first parameter is less than,
6477      * equal to, or greater than the second respectively. Otherwise,
6478      * the Closure is assumed to take a single parameter and return a
6479      * Comparable (typically an Integer) which is then used for
6480      * further comparison.
6481      *
6482      * @param self    an Iterator
6483      * @param closure a Closure used to determine the correct ordering
6484      * @return the minimum value
6485      * @see #min(java.util.Collection, groovy.lang.Closure)
6486      * @since 1.5.5
6487      */
6488     public static <T> T min(Iterator<T> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure closure) {
6489         return min((Iterable<T>)toList(self), closure);
6490     }
6491 
6492     /**
6493      * Selects the minimum value found from the Object array
6494      * using the closure to determine the correct ordering.
6495      * <p>
6496      * If the closure has two parameters
6497      * it is used like a traditional Comparator. I.e. it should compare
6498      * its two parameters for order, returning a negative integer,
6499      * zero, or a positive integer when the first parameter is less than,
6500      * equal to, or greater than the second respectively. Otherwise,
6501      * the Closure is assumed to take a single parameter and return a
6502      * Comparable (typically an Integer) which is then used for
6503      * further comparison.
6504      *
6505      * @param self    an array
6506      * @param closure a Closure used to determine the correct ordering
6507      * @return the minimum value
6508      * @see #min(java.util.Collection, groovy.lang.Closure)
6509      * @since 1.5.5
6510      */
6511     public static <T> T min(T[] self, @ClosureParams(FirstParam.Component.class) Closure closure) {
6512         return min((Iterable<T>)toList(self), closure);
6513     }
6514 
6515     /**
6516      * @deprecated Use the Iterable version of max instead
6517      * @see #max(Iterable)
6518      * @since 1.0
6519      */
6520     @Deprecated
6521     public static <T> T max(Collection<T> self) {
6522         return GroovyCollections.max((Iterable<T>)self);
6523     }
6524 
6525     /**
6526      * Adds max() method to Iterable objects.
6527      * <pre class="groovyTestCase">
6528      * assert 5 == [2,3,1,5,4].max()
6529      * </pre>
6530      *
6531      * @param self an Iterable
6532      * @return the maximum value
6533      * @see groovy.util.GroovyCollections#max(java.lang.Iterable)
6534      * @since 2.2.0
6535      */
6536     public static <T> T max(Iterable<T> self) {
6537         return GroovyCollections.max(self);
6538     }
6539 
6540     /**
6541      * Adds max() method to Iterator objects. The iterator will become
6542      * exhausted of elements after determining the maximum value.
6543      *
6544      * @param self an Iterator
6545      * @return the maximum value
6546      * @see groovy.util.GroovyCollections#max(java.util.Collection)
6547      * @since 1.5.5
6548      */
6549     public static <T> T max(Iterator<T> self) {
6550         return max((Iterable<T>)toList(self));
6551     }
6552 
6553     /**
6554      * Adds max() method to Object arrays.
6555      *
6556      * @param self an array
6557      * @return the maximum value
6558      * @see #max(java.util.Collection)
6559      * @since 1.5.5
6560      */
6561     public static <T> T max(T[] self) {
6562         return max((Iterable<T>)toList(self));
6563     }
6564 
6565     /**
6566      * @deprecated Use the Iterable version of max instead
6567      * @see #max(Iterable, Closure)
6568      * @since 1.0
6569      */
6570     @Deprecated
6571     public static <T> T max(Collection<T> self, Closure closure) {
6572         return max((Iterable<T>) self, closure);
6573     }
6574 
6575     /**
6576      * Selects the item in the iterable which when passed as a parameter to the supplied closure returns the
6577      * maximum value. A null return value represents the least possible return value, so any item for which
6578      * the supplied closure returns null, won't be selected (unless all items return null). If more than one item
6579      * has the maximum value, an arbitrary choice is made between the items having the maximum value.
6580      * <p>
6581      * If the closure has two parameters
6582      * it is used like a traditional Comparator. I.e. it should compare
6583      * its two parameters for order, returning a negative integer,
6584      * zero, or a positive integer when the first parameter is less than,
6585      * equal to, or greater than the second respectively. Otherwise,
6586      * the Closure is assumed to take a single parameter and return a
6587      * Comparable (typically an Integer) which is then used for
6588      * further comparison.
6589      * <pre class="groovyTestCase">assert "hello" == ["hello","hi","hey"].max { it.length() }</pre>
6590      * <pre class="groovyTestCase">assert "hello" == ["hello","hi","hey"].max { a, b -> a.length() <=> b.length() }</pre>
6591      * <pre class="groovyTestCase">
6592      * def pets = ['dog', 'elephant', 'anaconda']
6593      * def longestName = pets.max{ it.size() } // one of 'elephant' or 'anaconda'
6594      * assert longestName.size() == 8
6595      * </pre>
6596      *
6597      * @param self    an Iterable
6598      * @param closure a 1 or 2 arg Closure used to determine the correct ordering
6599      * @return an item from the Iterable having the maximum value returned by calling the supplied closure with that item as parameter or null for an empty Iterable
6600      * @since 2.2.0
6601      */
6602     public static <T> T max(Iterable<T> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure closure) {
6603         int params = closure.getMaximumNumberOfParameters();
6604         if (params != 1) {
6605             return max(self, new ClosureComparator<T>(closure));
6606         }
6607         boolean first = true;
6608         T answer = null;
6609         Object answerValue = null;
6610         for (T item : self) {
6611             Object value = closure.call(item);
6612             if (first) {
6613                 first = false;
6614                 answer = item;
6615                 answerValue = value;
6616             } else if (ScriptBytecodeAdapter.compareLessThan(answerValue, value)) {
6617                 answer = item;
6618                 answerValue = value;
6619             }
6620         }
6621         return answer;
6622     }
6623 
6624     /**
6625      * Selects the maximum value found from the Iterator
6626      * using the closure to determine the correct ordering.
6627      * The iterator will become exhausted of elements after this operation.
6628      * <p>
6629      * If the closure has two parameters
6630      * it is used like a traditional Comparator. I.e. it should compare
6631      * its two parameters for order, returning a negative integer,
6632      * zero, or a positive integer when the first parameter is less than,
6633      * equal to, or greater than the second respectively. Otherwise,
6634      * the Closure is assumed to take a single parameter and return a
6635      * Comparable (typically an Integer) which is then used for
6636      * further comparison.
6637      *
6638      * @param self    an Iterator
6639      * @param closure a Closure used to determine the correct ordering
6640      * @return the maximum value
6641      * @see #max(java.util.Collection, groovy.lang.Closure)
6642      * @since 1.5.5
6643      */
6644     public static <T> T max(Iterator<T> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure closure) {
6645         return max((Iterable<T>)toList(self), closure);
6646     }
6647 
6648     /**
6649      * Selects the maximum value found from the Object array
6650      * using the closure to determine the correct ordering.
6651      * <p>
6652      * If the closure has two parameters
6653      * it is used like a traditional Comparator. I.e. it should compare
6654      * its two parameters for order, returning a negative integer,
6655      * zero, or a positive integer when the first parameter is less than,
6656      * equal to, or greater than the second respectively. Otherwise,
6657      * the Closure is assumed to take a single parameter and return a
6658      * Comparable (typically an Integer) which is then used for
6659      * further comparison.
6660      *
6661      * @param self    an array
6662      * @param closure a Closure used to determine the correct ordering
6663      * @return the maximum value
6664      * @see #max(java.util.Collection, groovy.lang.Closure)
6665      * @since 1.5.5
6666      */
6667     public static <T> T max(T[] self, @ClosureParams(FirstParam.Component.class) Closure closure) {
6668         return max((Iterable<T>)toList(self), closure);
6669     }
6670 
6671     /**
6672      * @deprecated Use the Iterable version of max instead
6673      * @see #max(Iterable, Comparator)
6674      * @since 1.0
6675      */
6676     @Deprecated
6677     public static <T> T max(Collection<T> self, Comparator<T> comparator) {
6678         return max((Iterable<T>)self, comparator);
6679     }
6680 
6681     /**
6682      * Selects the maximum value found in the Iterable using the given comparator.
6683      * <pre class="groovyTestCase">
6684      * assert "hello" == ["hello","hi","hey"].max( { a, b -> a.length() <=> b.length() } as Comparator )
6685      * </pre>
6686      *
6687      * @param self       an Iterable
6688      * @param comparator a Comparator
6689      * @return the maximum value or null for an empty Iterable
6690      * @since 2.2.0
6691      */
6692     public static <T> T max(Iterable<T> self, Comparator<T> comparator) {
6693         T answer = null;
6694         boolean first = true;
6695         for (T value : self) {
6696             if (first) {
6697                 first = false;
6698                 answer = value;
6699             } else if (comparator.compare(value, answer) > 0) {
6700                 answer = value;
6701             }
6702         }
6703         return answer;
6704     }
6705 
6706     /**
6707      * Selects the maximum value found from the Iterator using the given comparator.
6708      *
6709      * @param self       an Iterator
6710      * @param comparator a Comparator
6711      * @return the maximum value
6712      * @since 1.5.5
6713      */
6714     public static <T> T max(Iterator<T> self, Comparator<T> comparator) {
6715         return max((Iterable<T>)toList(self), comparator);
6716     }
6717 
6718     /**
6719      * Selects the maximum value found from the Object array using the given comparator.
6720      *
6721      * @param self       an array
6722      * @param comparator a Comparator
6723      * @return the maximum value
6724      * @since 1.5.5
6725      */
6726     public static <T> T max(T[] self, Comparator<T> comparator) {
6727         return max((Iterable<T>)toList(self), comparator);
6728     }
6729 
6730     /**
6731      * Returns indices of the collection.
6732      * <p>
6733      * Example:
6734      * <pre class="groovyTestCase">
6735      * assert 0..2 == [5, 6, 7].indices
6736      * </pre>
6737      *
6738      * @param self a collection
6739      * @return an index range
6740      * @since 2.4.0
6741      */
6742     public static IntRange getIndices(Collection self) {
6743         return new IntRange(false, 0, self.size());
6744     }
6745 
6746     /**
6747      * Returns indices of the array.
6748      * <p>
6749      * Example:
6750      * <pre class="groovyTestCase">
6751      * String[] letters = ['a', 'b', 'c', 'd']
6752      * assert 0..<4 == letters.indices
6753      * </pre>
6754      *
6755      * @param self an array
6756      * @return an index range
6757      * @since 2.4.0
6758      */
6759     public static <T> IntRange getIndices(T[] self) {
6760         return new IntRange(false, 0, self.length);
6761     }
6762 
6763     /**
6764      * Provide the standard Groovy <code>size()</code> method for <code>Iterator</code>.
6765      * The iterator will become exhausted of elements after determining the size value.
6766      *
6767      * @param self an Iterator
6768      * @return the length of the Iterator
6769      * @since 1.5.5
6770      */
6771     public static int size(Iterator self) {
6772         int count = 0;
6773         while (self.hasNext()) {
6774             self.next();
6775             count++;
6776         }
6777         return count;
6778     }
6779 
6780     /**
6781      * Provide the standard Groovy <code>size()</code> method for <code>Iterable</code>.
6782      * <pre class="groovyTestCase">
6783      * def items = [1, 2, 3]
6784      * def iterable = { [ hasNext:{ !items.isEmpty() }, next:{ items.pop() } ] as Iterator } as Iterable
6785      * assert iterable.size() == 3
6786      * </pre>
6787      *
6788      * @param self an Iterable
6789      * @return the length of the Iterable
6790      * @since 2.3.8
6791      */
6792     public static int size(Iterable self) {
6793         return size(self.iterator());
6794     }
6795 
6796     /**
6797      * Provide the standard Groovy <code>size()</code> method for an array.
6798      *
6799      * @param self an Array of objects
6800      * @return the size (length) of the Array
6801      * @since 1.0
6802      */
6803     public static int size(Object[] self) {
6804         return self.length;
6805     }
6806 
6807     /**
6808      * Support the range subscript operator for a List.
6809      * <pre class="groovyTestCase">def list = [1, "a", 4.5, true]
6810      * assert list[1..2] == ["a", 4.5]</pre>
6811      *
6812      * @param self  a List
6813      * @param range a Range indicating the items to get
6814      * @return a new list instance based on range borders
6815      *
6816      * @since 1.0
6817      */
6818     public static <T> List<T> getAt(List<T> self, Range range) {
6819         RangeInfo info = subListBorders(self.size(), range);
6820 
6821         List<T> subList = self.subList(info.from, info.to);
6822         if (info.reverse) {
6823             subList = reverse(subList);
6824         }
6825 
6826         // trying to guess the concrete list type and create a new instance from it
6827         List<T> answer = createSimilarList(self, subList.size());
6828         answer.addAll(subList);
6829 
6830         return answer;
6831     }
6832 
6833 
6834     /**
6835      * Select a List of items from an eager or lazy List using a Collection to
6836      * identify the indices to be selected.
6837      * <pre class="groovyTestCase">def list = [].withDefault { 42 }
6838      * assert list[1,0,2] == [42, 42, 42]</pre>
6839      *
6840      * @param self    a ListWithDefault
6841      * @param indices a Collection of indices
6842      *
6843      * @return a new eager or lazy list of the values at the given indices
6844      */
6845     public static <T> List<T> getAt(ListWithDefault<T> self, Collection indices) {
6846         List<T> answer = ListWithDefault.newInstance(new ArrayList<T>(indices.size()), self.isLazyDefaultValues(), self.getInitClosure());
6847         for (Object value : indices) {
6848             if (value instanceof Range || value instanceof Collection) {
6849                 answer.addAll((List<T>) InvokerHelper.invokeMethod(self, "getAt", value));
6850             } else {
6851                 int idx = normaliseIndex(DefaultTypeTransformation.intUnbox(value), self.size());
6852                 answer.add(self.getAt(idx));
6853             }
6854         }
6855         return answer;
6856     }
6857 
6858     /**
6859      * Support the range subscript operator for an eager or lazy List.
6860      * <pre class="groovyTestCase">def list = [].withDefault { 42 }
6861      * assert list[1..2] == [null, 42]</pre>
6862      *
6863      * @param self  a ListWithDefault
6864      * @param range a Range indicating the items to get
6865      *
6866      * @return a new eager or lazy list instance based on range borders
6867      */
6868     public static <T> List<T> getAt(ListWithDefault<T> self, Range range) {
6869         RangeInfo info = subListBorders(self.size(), range);
6870 
6871         // if a positive index is accessed not initialized so far
6872         // initialization up to that index takes place
6873         if (self.size() < info.to) {
6874             self.get(info.to - 1);
6875         }
6876 
6877         List<T> answer = self.subList(info.from, info.to);
6878         if (info.reverse) {
6879             answer =  ListWithDefault.newInstance(reverse(answer), self.isLazyDefaultValues(), self.getInitClosure());
6880         } else {
6881             // instead of using the SubList backed by the parent list, a new ArrayList instance is used
6882             answer =  ListWithDefault.newInstance(new ArrayList<T>(answer), self.isLazyDefaultValues(), self.getInitClosure());
6883         }
6884 
6885         return answer;
6886     }
6887 
6888     /**
6889      * Support the range subscript operator for an eager or lazy List.
6890      * <pre class="groovyTestCase">def list = [true, 1, 3.4].withDefault{ 42 }
6891      * assert list[0..<0] == []</pre>
6892      *
6893      * @param self  a ListWithDefault
6894      * @param range a Range indicating the items to get
6895      *
6896      * @return a new list instance based on range borders
6897      *
6898      */
6899     public static <T> List<T> getAt(ListWithDefault<T> self, EmptyRange range) {
6900         return ListWithDefault.newInstance(new ArrayList<T>(), self.isLazyDefaultValues(), self.getInitClosure());
6901     }
6902 
6903     /**
6904      * Support the range subscript operator for a List.
6905      * <pre class="groovyTestCase">def list = [true, 1, 3.4]
6906      * assert list[0..<0] == []</pre>
6907      *
6908      * @param self  a List
6909      * @param range a Range indicating the items to get
6910      * @return a new list instance based on range borders
6911      *
6912      * @since 1.0
6913      */
6914     public static <T> List<T> getAt(List<T> self, EmptyRange range) {
6915         return createSimilarList(self, 0);
6916     }
6917 
6918     /**
6919      * Select a List of items from a List using a Collection to
6920      * identify the indices to be selected.
6921      * <pre class="groovyTestCase">def list = [true, 1, 3.4, false]
6922      * assert list[1,0,2] == [1, true, 3.4]</pre>
6923      *
6924      * @param self    a List
6925      * @param indices a Collection of indices
6926      * @return a new list of the values at the given indices
6927      * @since 1.0
6928      */
6929     public static <T> List<T> getAt(List<T> self, Collection indices) {
6930         List<T> answer = new ArrayList<T>(indices.size());
6931         for (Object value : indices) {
6932             if (value instanceof Range || value instanceof Collection) {
6933                 answer.addAll((List<T>)InvokerHelper.invokeMethod(self, "getAt", value));
6934             } else {
6935                 int idx = DefaultTypeTransformation.intUnbox(value);
6936                 answer.add(getAt(self, idx));
6937             }
6938         }
6939         return answer;
6940     }
6941 
6942     /**
6943      * Select a List of items from an array using a Collection to
6944      * identify the indices to be selected.
6945      *
6946      * @param self    an array
6947      * @param indices a Collection of indices
6948      * @return a new list of the values at the given indices
6949      * @since 1.0
6950      */
6951     public static <T> List<T> getAt(T[] self, Collection indices) {
6952         List<T> answer = new ArrayList<T>(indices.size());
6953         for (Object value : indices) {
6954             if (value instanceof Range) {
6955                 answer.addAll(getAt(self, (Range) value));
6956             } else if (value instanceof Collection) {
6957                 answer.addAll(getAt(self, (Collection) value));
6958             } else {
6959                 int idx = DefaultTypeTransformation.intUnbox(value);
6960                 answer.add(getAtImpl(self, idx));
6961             }
6962         }
6963         return answer;
6964     }
6965 
6966     /**
6967      * Creates a sub-Map containing the given keys. This method is similar to
6968      * List.subList() but uses keys rather than index ranges.
6969      * <pre class="groovyTestCase">assert [1:10, 2:20, 4:40].subMap( [2, 4] ) == [2:20, 4:40]</pre>
6970      *
6971      * @param map  a Map
6972      * @param keys a Collection of keys
6973      * @return a new Map containing the given keys
6974      * @since 1.0
6975      */
6976     public static <K, V> Map<K, V> subMap(Map<K, V> map, Collection<K> keys) {
6977         Map<K, V> answer = new LinkedHashMap<K, V>(keys.size());
6978         for (K key : keys) {
6979             if (map.containsKey(key)) {
6980                 answer.put(key, map.get(key));
6981             }
6982         }
6983         return answer;
6984     }
6985 
6986     /**
6987      * Creates a sub-Map containing the given keys. This method is similar to
6988      * List.subList() but uses keys rather than index ranges. The original
6989      * map is unaltered.
6990      * <pre class="groovyTestCase">
6991      * def orig = [1:10, 2:20, 3:30, 4:40]
6992      * assert orig.subMap([1, 3] as int[]) == [1:10, 3:30]
6993      * assert orig.subMap([2, 4] as Integer[]) == [2:20, 4:40]
6994      * assert orig.size() == 4
6995      * </pre>
6996      *
6997      * @param map  a Map
6998      * @param keys an array of keys
6999      * @return a new Map containing the given keys
7000      * @since 2.1.0
7001      */
7002     public static <K, V> Map<K, V> subMap(Map<K, V> map, K[] keys) {
7003         Map<K, V> answer = new LinkedHashMap<K, V>(keys.length);
7004         for (K key : keys) {
7005             if (map.containsKey(key)) {
7006                 answer.put(key, map.get(key));
7007             }
7008         }
7009         return answer;
7010     }
7011 
7012     /**
7013      * Looks up an item in a Map for the given key and returns the value - unless
7014      * there is no entry for the given key in which case add the default value
7015      * to the map and return that.
7016      * <pre class="groovyTestCase">def map=[:]
7017      * map.get("a", []) &lt;&lt; 5
7018      * assert map == [a:[5]]</pre>
7019      *
7020      * @param map          a Map
7021      * @param key          the key to lookup the value of
7022      * @param defaultValue the value to return and add to the map for this key if
7023      *                     there is no entry for the given key
7024      * @return the value of the given key or the default value, added to the map if the
7025      *         key did not exist
7026      * @since 1.0
7027      */
7028     public static <K, V> V get(Map<K, V> map, K key, V defaultValue) {
7029         if (!map.containsKey(key)) {
7030             map.put(key, defaultValue);
7031         }
7032         return map.get(key);
7033     }
7034 
7035     /**
7036      * Support the range subscript operator for an Array
7037      *
7038      * @param array an Array of Objects
7039      * @param range a Range
7040      * @return a range of a list from the range's from index up to but not
7041      *         including the range's to value
7042      * @since 1.0
7043      */
7044     public static <T> List<T> getAt(T[] array, Range range) {
7045         List<T> list = Arrays.asList(array);
7046         return getAt(list, range);
7047     }
7048 
7049     /**
7050      *
7051      * @param array an Array of Objects
7052      * @param range an IntRange
7053      * @return a range of a list from the range's from index up to but not
7054      *         including the range's to value
7055      * @since 1.0
7056      */
7057     public static <T> List<T> getAt(T[] array, IntRange range) {
7058         List<T> list = Arrays.asList(array);
7059         return getAt(list, range);
7060     }
7061 
7062     /**
7063      *
7064      * @param array an Array of Objects
7065      * @param range an EmptyRange
7066      * @return an empty Range
7067      * @since 1.5.0
7068      */
7069     public static <T> List<T> getAt(T[] array, EmptyRange range) {
7070         return new ArrayList<T>();
7071     }
7072 
7073     /**
7074      *
7075      * @param array an Array of Objects
7076      * @param range an ObjectRange
7077      * @return a range of a list from the range's from index up to but not
7078      *         including the range's to value
7079      * @since 1.0
7080      */
7081     public static <T> List<T> getAt(T[] array, ObjectRange range) {
7082         List<T> list = Arrays.asList(array);
7083         return getAt(list, range);
7084     }
7085 
7086     private static <T> T getAtImpl(T[] array, int idx) {
7087         return array[normaliseIndex(idx, array.length)];
7088     }
7089 
7090     /**
7091      * Allows conversion of arrays into a mutable List.
7092      *
7093      * @param array an Array of Objects
7094      * @return the array as a List
7095      * @since 1.0
7096      */
7097     public static <T> List<T> toList(T[] array) {
7098         return new ArrayList<T>(Arrays.asList(array));
7099     }
7100 
7101     /**
7102      * Support the subscript operator for a List.
7103      * <pre class="groovyTestCase">def list = [2, "a", 5.3]
7104      * assert list[1] == "a"</pre>
7105      *
7106      * @param self a List
7107      * @param idx  an index
7108      * @return the value at the given index
7109      * @since 1.0
7110      */
7111     public static <T> T getAt(List<T> self, int idx) {
7112         int size = self.size();
7113         int i = normaliseIndex(idx, size);
7114         if (i < size) {
7115             return self.get(i);
7116         } else {
7117             return null;
7118         }
7119     }
7120 
7121     /**
7122      * Support the subscript operator for an Iterator. The iterator
7123      * will be partially exhausted up until the idx entry after returning
7124      * if a +ve or 0 idx is used, or fully exhausted if a -ve idx is used
7125      * or no corresponding entry was found. Typical usage:
7126      * <pre class="groovyTestCase">
7127      * def iter = [2, "a", 5.3].iterator()
7128      * assert iter[1] == "a"
7129      * </pre>
7130      * A more elaborate example:
7131      * <pre class="groovyTestCase">
7132      * def items = [2, "a", 5.3]
7133      * def iter = items.iterator()
7134      * assert iter[-1] == 5.3
7135      * // iter exhausted, so reset
7136      * iter = items.iterator()
7137      * assert iter[1] == "a"
7138      * // iter partially exhausted so now idx starts after "a"
7139      * assert iter[0] == 5.3
7140      * </pre>
7141      *
7142      * @param self an Iterator
7143      * @param idx  an index value (-self.size() &lt;= idx &lt; self.size())
7144      * @return the value at the given index (after normalisation) or null if no corresponding value was found
7145      * @since 1.7.2
7146      */
7147     public static <T> T getAt(Iterator<T> self, int idx) {
7148         if (idx < 0) {
7149             // calculate whole list in this case
7150             // recommend avoiding -ve's as this is not as efficient
7151             List<T> list = toList(self);
7152             int adjustedIndex = idx + list.size();
7153             if (adjustedIndex < 0 || adjustedIndex >= list.size()) return null;
7154             return list.get(adjustedIndex);
7155         }
7156 
7157         int count = 0;
7158         while (self.hasNext()) {
7159             if (count == idx) {
7160                 return self.next();
7161             } else {
7162                 count++;
7163                 self.next();
7164             }
7165         }
7166 
7167         return null;
7168     }
7169 
7170     /**
7171      * Support the subscript operator for an Iterable. Typical usage:
7172      * <pre class="groovyTestCase">
7173      * // custom Iterable example:
7174      * class MyIterable implements Iterable {
7175      *   Iterator iterator() { [1, 2, 3].iterator() }
7176      * }
7177      * def myIterable = new MyIterable()
7178      * assert myIterable[1] == 2
7179      *
7180      * // Set example:
7181      * def set = [1,2,3] as LinkedHashSet
7182      * assert set[1] == 2
7183      * </pre>
7184      *
7185      * @param self an Iterable
7186      * @param idx  an index value (-self.size() &lt;= idx &lt; self.size()) but using -ve index values will be inefficient
7187      * @return the value at the given index (after normalisation) or null if no corresponding value was found
7188      * @since 2.1.0
7189      */
7190     public static <T> T getAt(Iterable<T> self, int idx) {
7191         return getAt(self.iterator(), idx);
7192     }
7193 
7194     /**
7195      * A helper method to allow lists to work with subscript operators.
7196      * <pre class="groovyTestCase">def list = [2, 3]
7197      * list[0] = 1
7198      * assert list == [1, 3]</pre>
7199      *
7200      * @param self  a List
7201      * @param idx   an index
7202      * @param value the value to put at the given index
7203      * @since 1.0
7204      */
7205     public static <T> void putAt(List<T> self, int idx, T value) {
7206         int size = self.size();
7207         idx = normaliseIndex(idx, size);
7208         if (idx < size) {
7209             self.set(idx, value);
7210         } else {
7211             while (size < idx) {
7212                 self.add(size++, null);
7213             }
7214             self.add(idx, value);
7215         }
7216     }
7217 
7218     /**
7219      * A helper method to allow lists to work with subscript operators.
7220      * <pre class="groovyTestCase">def list = ["a", true]
7221      * list[1..<1] = 5
7222      * assert list == ["a", 5, true]</pre>
7223      *
7224      * @param self  a List
7225      * @param range the (in this case empty) subset of the list to set
7226      * @param value the values to put at the given sublist or a Collection of values
7227      * @since 1.0
7228      */
7229     public static void putAt(List self, EmptyRange range, Object value) {
7230         RangeInfo info = subListBorders(self.size(), range);
7231         List sublist = self.subList(info.from, info.to);
7232         sublist.clear();
7233         if (value instanceof Collection) {
7234             Collection col = (Collection) value;
7235             if (col.isEmpty()) return;
7236             sublist.addAll(col);
7237         } else {
7238             sublist.add(value);
7239         }
7240     }
7241 
7242     /**
7243      * A helper method to allow lists to work with subscript operators.
7244      * <pre class="groovyTestCase">def list = ["a", true]
7245      * list[1..<1] = [4, 3, 2]
7246      * assert list == ["a", 4, 3, 2, true]</pre>
7247      *
7248      * @param self  a List
7249      * @param range the (in this case empty) subset of the list to set
7250      * @param value the Collection of values
7251      * @since 1.0
7252      * @see #putAt(java.util.List, groovy.lang.EmptyRange, java.lang.Object)
7253      */
7254     public static void putAt(List self, EmptyRange range, Collection value) {
7255         putAt(self, range, (Object)value);
7256     }
7257 
7258     private static <T> List<T> resizeListWithRangeAndGetSublist(List<T> self, IntRange range) {
7259         RangeInfo info = subListBorders(self.size(), range);
7260         int size = self.size();
7261         if (info.to >= size) {
7262             while (size < info.to) {
7263                 self.add(size++, null);
7264             }
7265         }
7266         List<T> sublist = self.subList(info.from, info.to);
7267         sublist.clear();
7268         return sublist;
7269     }
7270 
7271     /**
7272      * List subscript assignment operator when given a range as the index and
7273      * the assignment operand is a collection.
7274      * Example: <pre class="groovyTestCase">def myList = [4, 3, 5, 1, 2, 8, 10]
7275      * myList[3..5] = ["a", true]
7276      * assert myList == [4, 3, 5, "a", true, 10]</pre>
7277      *
7278      * Items in the given
7279      * range are replaced with items from the collection.
7280      *
7281      * @param self  a List
7282      * @param range the subset of the list to set
7283      * @param col   the collection of values to put at the given sublist
7284      * @since 1.5.0
7285      */
7286     public static void putAt(List self, IntRange range, Collection col) {
7287         List sublist = resizeListWithRangeAndGetSublist(self, range);
7288         if (col.isEmpty()) return;
7289         sublist.addAll(col);
7290     }
7291 
7292     /**
7293      * List subscript assignment operator when given a range as the index.
7294      * Example: <pre class="groovyTestCase">def myList = [4, 3, 5, 1, 2, 8, 10]
7295      * myList[3..5] = "b"
7296      * assert myList == [4, 3, 5, "b", 10]</pre>
7297      *
7298      * Items in the given
7299      * range are replaced with the operand.  The <code>value</code> operand is
7300      * always treated as a single value.
7301      *
7302      * @param self  a List
7303      * @param range the subset of the list to set
7304      * @param value the value to put at the given sublist
7305      * @since 1.0
7306      */
7307     public static void putAt(List self, IntRange range, Object value) {
7308         List sublist = resizeListWithRangeAndGetSublist(self, range);
7309         sublist.add(value);
7310     }
7311 
7312     /**
7313      * A helper method to allow lists to work with subscript operators.
7314      * <pre class="groovyTestCase">def list = ["a", true, 42, 9.4]
7315      * list[1, 4] = ["x", false]
7316      * assert list == ["a", "x", 42, 9.4, false]</pre>
7317      *
7318      * @param self   a List
7319      * @param splice the subset of the list to set
7320      * @param values the value to put at the given sublist
7321      * @since 1.0
7322      */
7323     public static void putAt(List self, List splice, List values) {
7324         if (splice.isEmpty()) {
7325             if ( ! values.isEmpty() )
7326                 throw new IllegalArgumentException("Trying to replace 0 elements with "+values.size()+" elements");
7327             return;
7328         }
7329         Object first = splice.iterator().next();
7330         if (first instanceof Integer) {
7331             if (values.size() != splice.size())
7332                 throw new IllegalArgumentException("Trying to replace "+splice.size()+" elements with "+values.size()+" elements");
7333             Iterator<?> valuesIter = values.iterator();
7334             for (Object index : splice) {
7335                 putAt(self, (Integer) index, valuesIter.next());
7336             }
7337         } else {
7338             throw new IllegalArgumentException("Can only index a List with another List of Integers, not a List of "+first.getClass().getName());
7339         }
7340     }
7341 
7342     /**
7343      * A helper method to allow lists to work with subscript operators.
7344      * <pre class="groovyTestCase">def list = ["a", true, 42, 9.4]
7345      * list[1, 3] = 5
7346      * assert list == ["a", 5, 42, 5]</pre>
7347      *
7348      * @param self   a List
7349      * @param splice the subset of the list to set
7350      * @param value  the value to put at the given sublist
7351      * @since 1.0
7352      */
7353     public static void putAt(List self, List splice, Object value) {
7354         if (splice.isEmpty()) {
7355             return;
7356         }
7357         Object first = splice.get(0);
7358         if (first instanceof Integer) {
7359             for (Object index : splice) {
7360                 self.set((Integer) index, value);
7361             }
7362         } else {
7363             throw new IllegalArgumentException("Can only index a List with another List of Integers, not a List of "+first.getClass().getName());
7364         }
7365     }
7366 
7367     // todo: remove after putAt(Splice) gets deleted
7368     @Deprecated
7369     protected static List getSubList(List self, List splice) {
7370         int left /* = 0 */;
7371         int right = 0;
7372         boolean emptyRange = false;
7373         if (splice.size() == 2) {
7374             left = DefaultTypeTransformation.intUnbox(splice.get(0));
7375             right = DefaultTypeTransformation.intUnbox(splice.get(1));
7376         } else if (splice instanceof IntRange) {
7377             IntRange range = (IntRange) splice;
7378             left = range.getFrom();
7379             right = range.getTo();
7380         } else if (splice instanceof EmptyRange) {
7381             RangeInfo info = subListBorders(self.size(), (EmptyRange) splice);
7382             left = info.from;
7383             emptyRange = true;
7384         } else {
7385             throw new IllegalArgumentException("You must specify a list of 2 indexes to create a sub-list");
7386         }
7387         int size = self.size();
7388         left = normaliseIndex(left, size);
7389         right = normaliseIndex(right, size);
7390         List sublist /* = null */;
7391         if (!emptyRange) {
7392             sublist = self.subList(left, right + 1);
7393         } else {
7394             sublist = self.subList(left, left);
7395         }
7396         return sublist;
7397     }
7398 
7399     /**
7400      * Support the subscript operator for a Map.
7401      * <pre class="groovyTestCase">def map = [a:10]
7402      * assert map["a"] == 10</pre>
7403      *
7404      * @param self a Map
7405      * @param key  an Object as a key for the map
7406      * @return the value corresponding to the given key
7407      * @since 1.0
7408      */
7409     public static <K,V> V getAt(Map<K,V> self, K key) {
7410         return self.get(key);
7411     }
7412 
7413     /**
7414      * Returns a new <code>Map</code> containing all entries from <code>left</code> and <code>right</code>,
7415      * giving precedence to <code>right</code>.  Any keys appearing in both Maps
7416      * will appear in the resultant map with values from the <code>right</code>
7417      * operand. If the <code>left</code> map is one of TreeMap, LinkedHashMap, Hashtable
7418      * or Properties, the returned Map will preserve that type, otherwise a HashMap will
7419      * be returned.
7420      * <p>
7421      * Roughly equivalent to <code>Map m = new HashMap(); m.putAll(left); m.putAll(right); return m;</code>
7422      * but with some additional logic to preserve the <code>left</code> Map type for common cases as
7423      * described above.
7424      * <pre class="groovyTestCase">
7425      * assert [a:10, b:20] + [a:5, c:7] == [a:5, b:20, c:7]
7426      * </pre>
7427      *
7428      * @param left  a Map
7429      * @param right a Map
7430      * @return a new Map containing all entries from left and right
7431      * @since 1.5.0
7432      */
7433     public static <K, V> Map<K, V> plus(Map<K, V> left, Map<K, V> right) {
7434         Map<K, V> map = cloneSimilarMap(left);
7435         map.putAll(right);
7436         return map;
7437     }
7438 
7439     /**
7440      * A helper method to allow maps to work with subscript operators
7441      *
7442      * @param self  a Map
7443      * @param key   an Object as a key for the map
7444      * @param value the value to put into the map
7445      * @return the value corresponding to the given key
7446      * @since 1.0
7447      */
7448     public static <K,V> V putAt(Map<K,V> self, K key, V value) {
7449         self.put(key, value);
7450         return value;
7451     }
7452 
7453     /**
7454      * Support the subscript operator for Collection.
7455      * <pre class="groovyTestCase">
7456      * assert [String, Long, Integer] == ["a",5L,2]["class"]
7457      * </pre>
7458      *
7459      * @param coll     a Collection
7460      * @param property a String
7461      * @return a List
7462      * @since 1.0
7463      */
7464     public static List getAt(Collection coll, String property) {
7465         List<Object> answer = new ArrayList<Object>(coll.size());
7466         return getAtIterable(coll, property, answer);
7467     }
7468 
7469     private static List getAtIterable(Iterable coll, String property, List<Object> answer) {
7470         for (Object item : coll) {
7471             if (item == null) continue;
7472             Object value;
7473             try {
7474                 value = InvokerHelper.getProperty(item, property);
7475             } catch (MissingPropertyExceptionNoStack mpe) {
7476                 String causeString = new MissingPropertyException(mpe.getProperty(), mpe.getType()).toString();
7477                 throw new MissingPropertyException("Exception evaluating property '" + property +
7478                         "' for " + coll.getClass().getName() + ", Reason: " + causeString);
7479             }
7480             answer.add(value);
7481         }
7482         return answer;
7483     }
7484 
7485     /**
7486      * A convenience method for creating an immutable map.
7487      *
7488      * @param self a Map
7489      * @return an immutable Map
7490      * @see java.util.Collections#unmodifiableMap(java.util.Map)
7491      * @since 1.0
7492      */
7493     public static <K,V> Map<K,V> asImmutable(Map<? extends K, ? extends V> self) {
7494         return Collections.unmodifiableMap(self);
7495     }
7496 
7497     /**
7498      * A convenience method for creating an immutable sorted map.
7499      *
7500      * @param self a SortedMap
7501      * @return an immutable SortedMap
7502      * @see java.util.Collections#unmodifiableSortedMap(java.util.SortedMap)
7503      * @since 1.0
7504      */
7505     public static <K,V> SortedMap<K,V> asImmutable(SortedMap<K, ? extends V> self) {
7506         return Collections.unmodifiableSortedMap(self);
7507     }
7508 
7509     /**
7510      * A convenience method for creating an immutable list
7511      *
7512      * @param self a List
7513      * @return an immutable List
7514      * @see java.util.Collections#unmodifiableList(java.util.List)
7515      * @since 1.0
7516      */
7517     public static <T> List<T> asImmutable(List<? extends T> self) {
7518         return Collections.unmodifiableList(self);
7519     }
7520 
7521     /**
7522      * A convenience method for creating an immutable list.
7523      *
7524      * @param self a Set
7525      * @return an immutable Set
7526      * @see java.util.Collections#unmodifiableSet(java.util.Set)
7527      * @since 1.0
7528      */
7529     public static <T> Set<T> asImmutable(Set<? extends T> self) {
7530         return Collections.unmodifiableSet(self);
7531     }
7532 
7533     /**
7534      * A convenience method for creating an immutable sorted set.
7535      *
7536      * @param self a SortedSet
7537      * @return an immutable SortedSet
7538      * @see java.util.Collections#unmodifiableSortedSet(java.util.SortedSet)
7539      * @since 1.0
7540      */
7541     public static <T> SortedSet<T> asImmutable(SortedSet<T> self) {
7542         return Collections.unmodifiableSortedSet(self);
7543     }
7544 
7545     /**
7546      * A convenience method for creating an immutable Collection.
7547      * <pre class="groovyTestCase">def mutable = [1,2,3]
7548      * def immutable = mutable.asImmutable()
7549      * mutable &lt;&lt; 4
7550      * try {
7551      *   immutable &lt;&lt; 4
7552      *   assert false
7553      * } catch (UnsupportedOperationException) {
7554      *   assert true
7555      * }</pre>
7556      *
7557      * @param self a Collection
7558      * @return an immutable Collection
7559      * @see java.util.Collections#unmodifiableCollection(java.util.Collection)
7560      * @since 1.5.0
7561      */
7562     public static <T> Collection<T> asImmutable(Collection<? extends T> self) {
7563         return Collections.unmodifiableCollection(self);
7564     }
7565 
7566     /**
7567      * A convenience method for creating a synchronized Map.
7568      *
7569      * @param self a Map
7570      * @return a synchronized Map
7571      * @see java.util.Collections#synchronizedMap(java.util.Map)
7572      * @since 1.0
7573      */
7574     public static <K,V> Map<K,V> asSynchronized(Map<K,V> self) {
7575         return Collections.synchronizedMap(self);
7576     }
7577 
7578     /**
7579      * A convenience method for creating a synchronized SortedMap.
7580      *
7581      * @param self a SortedMap
7582      * @return a synchronized SortedMap
7583      * @see java.util.Collections#synchronizedSortedMap(java.util.SortedMap)
7584      * @since 1.0
7585      */
7586     public static <K,V> SortedMap<K,V> asSynchronized(SortedMap<K,V> self) {
7587         return Collections.synchronizedSortedMap(self);
7588     }
7589 
7590     /**
7591      * A convenience method for creating a synchronized Collection.
7592      *
7593      * @param self a Collection
7594      * @return a synchronized Collection
7595      * @see java.util.Collections#synchronizedCollection(java.util.Collection)
7596      * @since 1.0
7597      */
7598     public static <T> Collection<T> asSynchronized(Collection<T> self) {
7599         return Collections.synchronizedCollection(self);
7600     }
7601 
7602     /**
7603      * A convenience method for creating a synchronized List.
7604      *
7605      * @param self a List
7606      * @return a synchronized List
7607      * @see java.util.Collections#synchronizedList(java.util.List)
7608      * @since 1.0
7609      */
7610     public static <T> List<T> asSynchronized(List<T> self) {
7611         return Collections.synchronizedList(self);
7612     }
7613 
7614     /**
7615      * A convenience method for creating a synchronized Set.
7616      *
7617      * @param self a Set
7618      * @return a synchronized Set
7619      * @see java.util.Collections#synchronizedSet(java.util.Set)
7620      * @since 1.0
7621      */
7622     public static <T> Set<T> asSynchronized(Set<T> self) {
7623         return Collections.synchronizedSet(self);
7624     }
7625 
7626     /**
7627      * A convenience method for creating a synchronized SortedSet.
7628      *
7629      * @param self a SortedSet
7630      * @return a synchronized SortedSet
7631      * @see java.util.Collections#synchronizedSortedSet(java.util.SortedSet)
7632      * @since 1.0
7633      */
7634     public static <T> SortedSet<T> asSynchronized(SortedSet<T> self) {
7635         return Collections.synchronizedSortedSet(self);
7636     }
7637 
7638     /**
7639      * Synonym for {@link #toSpreadMap(java.util.Map)}.
7640      * @param self a map
7641      * @return a newly created SpreadMap
7642      * @since 1.0
7643      */
7644     public static SpreadMap spread(Map self) {
7645         return toSpreadMap(self);
7646     }
7647 
7648     /**
7649      * Returns a new <code>SpreadMap</code> from this map.
7650      * <p>
7651      * The example below shows the various possible use cases:
7652      * <pre class="groovyTestCase">
7653      * def fn(Map m) { return m.a + m.b + m.c + m.d }
7654      *
7655      * assert fn(a:1, b:2, c:3, d:4) == 10
7656      * assert fn(a:1, *:[b:2, c:3], d:4) == 10
7657      * assert fn([a:1, b:2, c:3, d:4].toSpreadMap()) == 10
7658      * assert fn((['a', 1, 'b', 2, 'c', 3, 'd', 4] as Object[]).toSpreadMap()) == 10
7659      * assert fn(['a', 1, 'b', 2, 'c', 3, 'd', 4].toSpreadMap()) == 10
7660      * assert fn(['abcd'.toList(), 1..4].transpose().flatten().toSpreadMap()) == 10
7661      * </pre>
7662      * Note that toSpreadMap() is not normally used explicitly but under the covers by Groovy.
7663      *
7664      * @param self a map to be converted into a SpreadMap
7665      * @return a newly created SpreadMap if this map is not null and its size is positive.
7666      * @see groovy.lang.SpreadMap#SpreadMap(java.util.Map)
7667      * @since 1.0
7668      */
7669     public static SpreadMap toSpreadMap(Map self) {
7670         if (self == null)
7671             throw new GroovyRuntimeException("Fail to convert Map to SpreadMap, because it is null.");
7672         else
7673             return new SpreadMap(self);
7674     }
7675 
7676     /**
7677      * Creates a spreadable map from this array.
7678      * <p>
7679      * @param self an object array
7680      * @return a newly created SpreadMap
7681      * @see groovy.lang.SpreadMap#SpreadMap(java.lang.Object[])
7682      * @see #toSpreadMap(java.util.Map)
7683      * @since 1.0
7684      */
7685     public static SpreadMap toSpreadMap(Object[] self) {
7686         if (self == null)
7687             throw new GroovyRuntimeException("Fail to convert Object[] to SpreadMap, because it is null.");
7688         else if (self.length % 2 != 0)
7689             throw new GroovyRuntimeException("Fail to convert Object[] to SpreadMap, because it's size is not even.");
7690         else
7691             return new SpreadMap(self);
7692     }
7693 
7694     /**
7695      * Creates a spreadable map from this list.
7696      * <p>
7697      * @param self a list
7698      * @return a newly created SpreadMap
7699      * @see groovy.lang.SpreadMap#SpreadMap(java.util.List)
7700      * @see #toSpreadMap(java.util.Map)
7701      * @since 1.8.0
7702      */
7703     public static SpreadMap toSpreadMap(List self) {
7704         if (self == null)
7705             throw new GroovyRuntimeException("Fail to convert List to SpreadMap, because it is null.");
7706         else if (self.size() % 2 != 0)
7707             throw new GroovyRuntimeException("Fail to convert List to SpreadMap, because it's size is not even.");
7708         else
7709             return new SpreadMap(self);
7710     }
7711 
7712     /**
7713      * Creates a spreadable map from this iterable.
7714      * <p>
7715      * @param self an iterable
7716      * @return a newly created SpreadMap
7717      * @see groovy.lang.SpreadMap#SpreadMap(java.util.List)
7718      * @see #toSpreadMap(java.util.Map)
7719      * @since 2.4.0
7720      */
7721     public static SpreadMap toSpreadMap(Iterable self) {
7722         if (self == null)
7723             throw new GroovyRuntimeException("Fail to convert Iterable to SpreadMap, because it is null.");
7724         else
7725             return toSpreadMap(asList(self));
7726     }
7727 
7728     /**
7729      * Wraps a map using the decorator pattern with a wrapper that intercepts all calls
7730      * to <code>get(key)</code>. If an unknown key is found, a default value will be
7731      * stored into the Map before being returned. The default value stored will be the
7732      * result of calling the supplied Closure with the key as the parameter to the Closure.
7733      * Example usage:
7734      * <pre class="groovyTestCase">
7735      * def map = [a:1, b:2].withDefault{ k -> k.toCharacter().isLowerCase() ? 10 : -10 }
7736      * def expected = [a:1, b:2, c:10, D:-10]
7737      * assert expected.every{ e -> e.value == map[e.key] }
7738      *
7739      * def constMap = [:].withDefault{ 42 }
7740      * assert constMap.foo == 42
7741      * assert constMap.size() == 1
7742      * </pre>
7743      *
7744      * @param self a Map
7745      * @param init a Closure which is passed the unknown key
7746      * @return the wrapped Map
7747      * @since 1.7.1
7748      */
7749     public static <K, V> Map<K, V> withDefault(Map<K, V> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure init) {
7750         return MapWithDefault.newInstance(self, init);
7751     }
7752 
7753     /**
7754      * An alias for <code>withLazyDefault</code> which decorates a list allowing
7755      * it to grow when called with index values outside the normal list bounds.
7756      *
7757      * @param self a List
7758      * @param init a Closure with the target index as parameter which generates the default value
7759      * @return the decorated List
7760      * @see #withLazyDefault(java.util.List, groovy.lang.Closure)
7761      * @see #withEagerDefault(java.util.List, groovy.lang.Closure)
7762      * @since 1.8.7
7763      */
7764     public static <T> List<T> withDefault(List<T> self, Closure init) {
7765         return withLazyDefault(self, init);
7766     }
7767 
7768     /**
7769      * Decorates a list allowing it to grow when called with a non-existent index value.
7770      * When called with such values, the list is grown in size and a default value
7771      * is placed in the list by calling a supplied <code>init</code> Closure. Subsequent
7772      * retrieval operations if finding a null value in the list assume it was set
7773      * as null from an earlier growing operation and again call the <code>init</code> Closure
7774      * to populate the retrieved value; consequently the list can't be used to store null values.
7775      * <p>
7776      * How it works: The decorated list intercepts all calls
7777      * to <code>getAt(index)</code> and <code>get(index)</code>. If an index greater than
7778      * or equal to the current <code>size()</code> is used, the list will grow automatically
7779      * up to the specified index. Gaps will be filled by {@code null}. If a default value
7780      * should also be used to fill gaps instead of {@code null}, use <code>withEagerDefault</code>.
7781      * If <code>getAt(index)</code> or <code>get(index)</code> are called and a null value
7782      * is found, it is assumed that the null value was a consequence of an earlier grow list
7783      * operation and the <code>init</code> Closure is called to populate the value.
7784      * <p>
7785      * Example usage:
7786      * <pre class="groovyTestCase">
7787      * def list = [0, 1].withLazyDefault{ 42 }
7788      * assert list[0] == 0
7789      * assert list[1] == 1
7790      * assert list[3] == 42   // default value
7791      * assert list == [0, 1, null, 42] // gap filled with null
7792      *
7793      * // illustrate using the index when generating default values
7794      * def list2 = [5].withLazyDefault{ index -> index * index }
7795      * assert list2[3] == 9
7796      * assert list2 == [5, null, null, 9]
7797      * assert list2[2] == 4
7798      * assert list2 == [5, null, 4, 9]
7799      *
7800      * // illustrate what happens with null values
7801      * list2[2] = null
7802      * assert list2[2] == 4
7803      * </pre>
7804      *
7805      * @param self a List
7806      * @param init a Closure with the target index as parameter which generates the default value
7807      * @return the decorated List
7808      * @since 1.8.7
7809      */
7810     public static <T> List<T> withLazyDefault(List<T> self, Closure init) {
7811         return ListWithDefault.newInstance(self, true, init);
7812     }
7813 
7814     /**
7815      * Decorates a list allowing it to grow when called with a non-existent index value.
7816      * When called with such values, the list is grown in size and a default value
7817      * is placed in the list by calling a supplied <code>init</code> Closure. Null values
7818      * can be stored in the list.
7819      * <p>
7820      * How it works: The decorated list intercepts all calls
7821      * to <code>getAt(index)</code> and <code>get(index)</code>. If an index greater than
7822      * or equal to the current <code>size()</code> is used, the list will grow automatically
7823      * up to the specified index. Gaps will be filled by calling the <code>init</code> Closure.
7824      * If generating a default value is a costly operation consider using <code>withLazyDefault</code>.
7825      * <p>
7826      * Example usage:
7827      * <pre class="groovyTestCase">
7828      * def list = [0, 1].withEagerDefault{ 42 }
7829      * assert list[0] == 0
7830      * assert list[1] == 1
7831      * assert list[3] == 42   // default value
7832      * assert list == [0, 1, 42, 42]   // gap filled with default value
7833      *
7834      * // illustrate using the index when generating default values
7835      * def list2 = [5].withEagerDefault{ index -> index * index }
7836      * assert list2[3] == 9
7837      * assert list2 == [5, 1, 4, 9]
7838      *
7839      * // illustrate what happens with null values
7840      * list2[2] = null
7841      * assert list2[2] == null
7842      * assert list2 == [5, 1, null, 9]
7843      * </pre>
7844      *
7845      * @param self a List
7846      * @param init a Closure with the target index as parameter which generates the default value
7847      * @return the wrapped List
7848      * @since 1.8.7
7849      */
7850     public static <T> List<T> withEagerDefault(List<T> self, Closure init) {
7851         return ListWithDefault.newInstance(self, false, init);
7852     }
7853 
7854     /**
7855      * Zips an Iterable with indices in (value, index) order.
7856      * <p/>
7857      * Example usage:
7858      * <pre class="groovyTestCase">
7859      * assert [["a", 0], ["b", 1]] == ["a", "b"].withIndex()
7860      * assert ["0: a", "1: b"] == ["a", "b"].withIndex().collect { str, idx -> "$idx: $str" }
7861      * </pre>
7862      *
7863      * @param self an Iterable
7864      * @return a zipped list with indices
7865      * @see #indexed(Iterable)
7866      * @since 2.4.0
7867      */
7868     public static <E> List<Tuple2<E, Integer>> withIndex(Iterable<E> self) {
7869         return withIndex(self, 0);
7870     }
7871 
7872     /**
7873      * Zips an Iterable with indices in (index, value) order.
7874      * <p/>
7875      * Example usage:
7876      * <pre class="groovyTestCase">
7877      * assert [0: "a", 1: "b"] == ["a", "b"].indexed()
7878      * assert ["0: a", "1: b"] == ["a", "b"].indexed().collect { idx, str -> "$idx: $str" }
7879      * </pre>
7880      *
7881      * @param self an Iterable
7882      * @return a zipped map with indices
7883      * @see #withIndex(Iterable)
7884      * @since 2.4.0
7885      */
7886     public static <E> Map<Integer, E> indexed(Iterable<E> self) {
7887         return indexed(self, 0);
7888     }
7889 
7890     /**
7891      * Zips an Iterable with indices in (value, index) order.
7892      * <p/>
7893      * Example usage:
7894      * <pre class="groovyTestCase">
7895      * assert [["a", 5], ["b", 6]] == ["a", "b"].withIndex(5)
7896      * assert ["1: a", "2: b"] == ["a", "b"].withIndex(1).collect { str, idx -> "$idx: $str" }
7897      * </pre>
7898      *
7899      * @param self   an Iterable
7900      * @param offset an index to start from
7901      * @return a zipped list with indices
7902      * @see #indexed(Iterable, int)
7903      * @since 2.4.0
7904      */
7905     public static <E> List<Tuple2<E, Integer>> withIndex(Iterable<E> self, int offset) {
7906         return toList(withIndex(self.iterator(), offset));
7907     }
7908 
7909     /**
7910      * Zips an Iterable with indices in (index, value) order.
7911      * <p/>
7912      * Example usage:
7913      * <pre class="groovyTestCase">
7914      * assert [5: "a", 6: "b"] == ["a", "b"].indexed(5)
7915      * assert ["1: a", "2: b"] == ["a", "b"].indexed(1).collect { idx, str -> "$idx: $str" }
7916      * </pre>
7917      *
7918      * @param self   an Iterable
7919      * @param offset an index to start from
7920      * @return a Map (since the keys/indices are unique) containing the elements from the iterable zipped with indices
7921      * @see #withIndex(Iterable, int)
7922      * @since 2.4.0
7923      */
7924     public static <E> Map<Integer, E> indexed(Iterable<E> self, int offset) {
7925         LinkedHashMap<Integer, E> result = new LinkedHashMap<Integer, E>();
7926         Iterator<Tuple2<Integer, E>> indexed = indexed(self.iterator(), offset);
7927         while (indexed.hasNext()) {
7928             Tuple2<Integer, E> next = indexed.next();
7929             result.put(next.getFirst(), next.getSecond());
7930         }
7931         return result;
7932     }
7933 
7934     /**
7935      * Zips an iterator with indices in (value, index) order.
7936      * <p/>
7937      * Example usage:
7938      * <pre class="groovyTestCase">
7939      * assert [["a", 0], ["b", 1]] == ["a", "b"].iterator().withIndex().toList()
7940      * assert ["0: a", "1: b"] == ["a", "b"].iterator().withIndex().collect { str, idx -> "$idx: $str" }.toList()
7941      * </pre>
7942      *
7943      * @param self an iterator
7944      * @return a zipped iterator with indices
7945      * @see #indexed(Iterator)
7946      * @since 2.4.0
7947      */
7948     public static <E> Iterator<Tuple2<E, Integer>> withIndex(Iterator<E> self) {
7949         return withIndex(self, 0);
7950     }
7951 
7952     /**
7953      * Zips an iterator with indices in (index, value) order.
7954      * <p/>
7955      * Example usage:
7956      * <pre class="groovyTestCase">
7957      * assert [[0, "a"], [1, "b"]] == ["a", "b"].iterator().indexed().collect{ e -> [e.key, e.value] }
7958      * assert ["0: a", "1: b"] == ["a", "b"].iterator().indexed().collect { idx, str -> "$idx: $str" }.toList()
7959      * </pre>
7960      *
7961      * @param self an iterator
7962      * @return a zipped iterator with indices
7963      * @see #withIndex(Iterator)
7964      * @since 2.4.0
7965      */
7966     public static <E> Iterator<Tuple2<Integer, E>> indexed(Iterator<E> self) {
7967         return indexed(self, 0);
7968     }
7969 
7970     /**
7971      * Zips an iterator with indices in (value, index) order.
7972      * <p/>
7973      * Example usage:
7974      * <pre class="groovyTestCase">
7975      * assert [["a", 5], ["b", 6]] == ["a", "b"].iterator().withIndex(5).toList()
7976      * assert ["1: a", "2: b"] == ["a", "b"].iterator().withIndex(1).collect { str, idx -> "$idx: $str" }.toList()
7977      * </pre>
7978      *
7979      * @param self   an iterator
7980      * @param offset an index to start from
7981      * @return a zipped iterator with indices
7982      * @see #indexed(Iterator, int)
7983      * @since 2.4.0
7984      */
7985     public static <E> Iterator<Tuple2<E, Integer>> withIndex(Iterator<E> self, int offset) {
7986         return new ZipPostIterator<E>(self, offset);
7987     }
7988 
7989     /**
7990      * Zips an iterator with indices in (index, value) order.
7991      * <p/>
7992      * Example usage:
7993      * <pre class="groovyTestCase">
7994      * assert [[5, "a"], [6, "b"]] == ["a", "b"].iterator().indexed(5).toList()
7995      * assert ["a: 1", "b: 2"] == ["a", "b"].iterator().indexed(1).collect { idx, str -> "$str: $idx" }.toList()
7996      * </pre>
7997      *
7998      * @param self   an iterator
7999      * @param offset an index to start from
8000      * @return a zipped iterator with indices
8001      * @see #withIndex(Iterator, int)
8002      * @since 2.4.0
8003      */
8004     public static <E> Iterator<Tuple2<Integer, E>> indexed(Iterator<E> self, int offset) {
8005         return new ZipPreIterator<E>(self, offset);
8006     }
8007 
8008     private static final class ZipPostIterator<E> implements Iterator<Tuple2<E, Integer>> {
8009         private final Iterator<E> delegate;
8010         private int index;
8011 
8012         private ZipPostIterator(Iterator<E> delegate, int offset) {
8013             this.delegate = delegate;
8014             this.index = offset;
8015         }
8016 
8017         public boolean hasNext() {
8018             return delegate.hasNext();
8019         }
8020 
8021         public Tuple2<E, Integer> next() {
8022             if (!hasNext()) throw new NoSuchElementException();
8023             return new Tuple2<E, Integer>(delegate.next(), index++);
8024         }
8025 
8026         public void remove() {
8027             delegate.remove();
8028         }
8029     }
8030 
8031     private static final class ZipPreIterator<E> implements Iterator<Tuple2<Integer, E>> {
8032         private final Iterator<E> delegate;
8033         private int index;
8034 
8035         private ZipPreIterator(Iterator<E> delegate, int offset) {
8036             this.delegate = delegate;
8037             this.index = offset;
8038         }
8039 
8040         public boolean hasNext() {
8041             return delegate.hasNext();
8042         }
8043 
8044         public Tuple2<Integer, E> next() {
8045             if (!hasNext()) throw new NoSuchElementException();
8046             return new Tuple2<Integer, E>(index++, delegate.next());
8047         }
8048 
8049         public void remove() {
8050             delegate.remove();
8051         }
8052     }
8053 
8054     /**
8055      * @deprecated Use the Iterable version of sort instead
8056      * @see #sort(Iterable,boolean)
8057      * @since 1.0
8058      */
8059     @Deprecated
8060     public static <T> List<T> sort(Collection<T> self) {
8061         return sort((Iterable<T>) self, true);
8062     }
8063 
8064     /**
8065      * Sorts the Collection. Assumes that the collection items are comparable
8066      * and uses their natural ordering to determine the resulting order.
8067      * If the Collection is a List, it is sorted in place and returned.
8068      * Otherwise, the elements are first placed into a new list which is then
8069      * sorted and returned - leaving the original Collection unchanged.
8070      * <pre class="groovyTestCase">assert [1,2,3] == [3,1,2].sort()</pre>
8071      *
8072      * @param self the Iterable to be sorted
8073      * @return the sorted Iterable as a List
8074      * @see #sort(Collection, boolean)
8075      * @since 2.2.0
8076      */
8077     public static <T> List<T> sort(Iterable<T> self) {
8078         return sort(self, true);
8079     }
8080 
8081     /**
8082      * @deprecated Use the Iterable version of sort instead
8083      * @see #sort(Iterable, boolean)
8084      * @since 1.8.1
8085      */
8086     @Deprecated
8087     public static <T> List<T> sort(Collection<T> self, boolean mutate) {
8088         return sort((Iterable<T>) self, mutate);
8089     }
8090 
8091     /**
8092      * Sorts the Iterable. Assumes that the Iterable items are
8093      * comparable and uses their natural ordering to determine the resulting order.
8094      * If the Iterable is a List and mutate is true,
8095      * it is sorted in place and returned. Otherwise, the elements are first placed
8096      * into a new list which is then sorted and returned - leaving the original Iterable unchanged.
8097      * <pre class="groovyTestCase">assert [1,2,3] == [3,1,2].sort()</pre>
8098      * <pre class="groovyTestCase">
8099      * def orig = [1, 3, 2]
8100      * def sorted = orig.sort(false)
8101      * assert orig == [1, 3, 2]
8102      * assert sorted == [1, 2, 3]
8103      * </pre>
8104      *
8105      * @param self   the iterable to be sorted
8106      * @param mutate false will always cause a new list to be created, true will mutate lists in place
8107      * @return the sorted iterable as a List
8108      * @since 2.2.0
8109      */
8110     public static <T> List<T> sort(Iterable<T> self, boolean mutate) {
8111         List<T> answer = mutate ? asList(self) : toList(self);
8112         Collections.sort(answer, new NumberAwareComparator<T>());
8113         return answer;
8114     }
8115 
8116     /**
8117      * Sorts the elements from the given map into a new ordered map using
8118      * the closure as a comparator to determine the ordering.
8119      * The original map is unchanged.
8120      * <pre class="groovyTestCase">def map = [a:5, b:3, c:6, d:4].sort { a, b -> a.value <=> b.value }
8121      * assert map == [b:3, d:4, a:5, c:6]</pre>
8122      *
8123      * @param self the original unsorted map
8124      * @param closure a Closure used as a comparator
8125      * @return the sorted map
8126      * @since 1.6.0
8127      */
8128     public static <K, V> Map<K, V> sort(Map<K, V> self, @ClosureParams(value=FromString.class, options={"Map.Entry<K,V>","Map.Entry<K,V>,Map.Entry<K,V>"}) Closure closure) {
8129         Map<K, V> result = new LinkedHashMap<K, V>();
8130         List<Map.Entry<K, V>> entries = asList((Iterable<Map.Entry<K, V>>) self.entrySet());
8131         sort((Iterable<Map.Entry<K, V>>) entries, closure);
8132         for (Map.Entry<K, V> entry : entries) {
8133             result.put(entry.getKey(), entry.getValue());
8134         }
8135         return result;
8136     }
8137 
8138     /**
8139      * Sorts the elements from the given map into a new ordered Map using
8140      * the specified key comparator to determine the ordering.
8141      * The original map is unchanged.
8142      * <pre class="groovyTestCase">def map = [ba:3, cz:6, ab:5].sort({ a, b -> a[-1] <=> b[-1] } as Comparator)
8143      * assert map*.value == [3, 5, 6]</pre>
8144      *
8145      * @param self the original unsorted map
8146      * @param comparator a Comparator
8147      * @return the sorted map
8148      * @since 1.7.2
8149      */
8150     public static <K, V> Map<K, V> sort(Map<K, V> self, Comparator<K> comparator) {
8151         Map<K, V> result = new TreeMap<K, V>(comparator);
8152         result.putAll(self);
8153         return result;
8154     }
8155 
8156     /**
8157      * Sorts the elements from the given map into a new ordered Map using
8158      * the natural ordering of the keys to determine the ordering.
8159      * The original map is unchanged.
8160      * <pre class="groovyTestCase">map = [ba:3, cz:6, ab:5].sort()
8161      * assert map*.value == [5, 3, 6]
8162      * </pre>
8163      *
8164      * @param self the original unsorted map
8165      * @return the sorted map
8166      * @since 1.7.2
8167      */
8168     public static <K, V> Map<K, V> sort(Map<K, V> self) {
8169         return new TreeMap<K, V>(self);
8170     }
8171 
8172     /**
8173      * Modifies this array so that its elements are in sorted order.
8174      * The array items are assumed to be comparable.
8175      *
8176      * @param self the array to be sorted
8177      * @return the sorted array
8178      * @since 1.5.5
8179      */
8180     public static <T> T[] sort(T[] self) {
8181         Arrays.sort(self, new NumberAwareComparator<T>());
8182         return self;
8183     }
8184 
8185     /**
8186      * Sorts the given array into sorted order.
8187      * The array items are assumed to be comparable.
8188      * If mutate is true, the array is sorted in place and returned. Otherwise, a new sorted
8189      * array is returned and the original array remains unchanged.
8190      * <pre class="groovyTestCase">
8191      * def orig = ["hello","hi","Hey"] as String[]
8192      * def sorted = orig.sort(false)
8193      * assert orig == ["hello","hi","Hey"] as String[]
8194      * assert sorted == ["Hey","hello","hi"] as String[]
8195      * orig.sort(true)
8196      * assert orig == ["Hey","hello","hi"] as String[]
8197      * </pre>
8198      *
8199      * @param self   the array to be sorted
8200      * @param mutate false will always cause a new array to be created, true will mutate the array in place
8201      * @return the sorted array
8202      * @since 1.8.1
8203      */
8204     public static <T> T[] sort(T[] self, boolean mutate) {
8205         T[] answer = mutate ? self : self.clone();
8206         Arrays.sort(answer, new NumberAwareComparator<T>());
8207         return answer;
8208     }
8209 
8210     /**
8211      * Sorts the given iterator items into a sorted iterator. The items are
8212      * assumed to be comparable. The original iterator will become
8213      * exhausted of elements after completing this method call.
8214      * A new iterator is produced that traverses the items in sorted order.
8215      *
8216      * @param self the Iterator to be sorted
8217      * @return the sorted items as an Iterator
8218      * @since 1.5.5
8219      */
8220     public static <T> Iterator<T> sort(Iterator<T> self) {
8221         return sort((Iterable<T>) toList(self)).listIterator();
8222     }
8223 
8224     /**
8225      * Sorts the given iterator items into a sorted iterator using the comparator. The
8226      * original iterator will become exhausted of elements after completing this method call.
8227      * A new iterator is produced that traverses the items in sorted order.
8228      *
8229      * @param self       the Iterator to be sorted
8230      * @param comparator a Comparator used for comparing items
8231      * @return the sorted items as an Iterator
8232      * @since 1.5.5
8233      */
8234     public static <T> Iterator<T> sort(Iterator<T> self, Comparator<T> comparator) {
8235         return sort((Iterable<T>) toList(self), true, comparator).listIterator();
8236     }
8237 
8238     /**
8239      * @deprecated Use the Iterable version of sort instead
8240      * @see #sort(Iterable, boolean, Comparator)
8241      * @since 1.0
8242      */
8243     @Deprecated
8244     public static <T> List<T> sort(Collection<T> self, Comparator<T> comparator) {
8245         return sort((Iterable<T>) self, true, comparator);
8246     }
8247 
8248     /**
8249      * @deprecated Use the Iterable version of sort instead
8250      * @see #sort(Iterable, boolean, Comparator)
8251      * @since 1.8.1
8252      */
8253     @Deprecated
8254     public static <T> List<T> sort(Collection<T> self, boolean mutate, Comparator<T> comparator) {
8255         return sort((Iterable<T>) self, mutate, comparator);
8256     }
8257 
8258     /**
8259      * Sorts the Iterable using the given Comparator. If the Iterable is a List and mutate
8260      * is true, it is sorted in place and returned. Otherwise, the elements are first placed
8261      * into a new list which is then sorted and returned - leaving the original Iterable unchanged.
8262      * <pre class="groovyTestCase">
8263      * assert ["hi","hey","hello"] == ["hello","hi","hey"].sort( { a, b -> a.length() <=> b.length() } as Comparator )
8264      * </pre>
8265      * <pre class="groovyTestCase">
8266      * def orig = ["hello","hi","Hey"]
8267      * def sorted = orig.sort(false, String.CASE_INSENSITIVE_ORDER)
8268      * assert orig == ["hello","hi","Hey"]
8269      * assert sorted == ["hello","Hey","hi"]
8270      * </pre>
8271      *
8272      * @param self       the Iterable to be sorted
8273      * @param mutate     false will always cause a new list to be created, true will mutate lists in place
8274      * @param comparator a Comparator used for the comparison
8275      * @return a sorted List
8276      * @since 2.2.0
8277      */
8278     public static <T> List<T> sort(Iterable<T> self, boolean mutate, Comparator<T> comparator) {
8279         List<T> list = mutate ? asList(self) : toList(self);
8280         Collections.sort(list, comparator);
8281         return list;
8282     }
8283 
8284     /**
8285      * Sorts the given array into sorted order using the given comparator.
8286      *
8287      * @param self the array to be sorted
8288      * @param comparator a Comparator used for the comparison
8289      * @return the sorted array
8290      * @since 1.5.5
8291      */
8292     public static <T> T[] sort(T[] self, Comparator<T> comparator) {
8293         return sort(self, true, comparator);
8294     }
8295 
8296     /**
8297      * Modifies this array so that its elements are in sorted order as determined by the given comparator.
8298      * If mutate is true, the array is sorted in place and returned. Otherwise, a new sorted
8299      * array is returned and the original array remains unchanged.
8300      * <pre class="groovyTestCase">
8301      * def orig = ["hello","hi","Hey"] as String[]
8302      * def sorted = orig.sort(false, String.CASE_INSENSITIVE_ORDER)
8303      * assert orig == ["hello","hi","Hey"] as String[]
8304      * assert sorted == ["hello","Hey","hi"] as String[]
8305      * orig.sort(true, String.CASE_INSENSITIVE_ORDER)
8306      * assert orig == ["hello","Hey","hi"] as String[]
8307      * </pre>
8308      *
8309      * @param self       the array containing elements to be sorted
8310      * @param mutate     false will always cause a new array to be created, true will mutate arrays in place
8311      * @param comparator a Comparator used for the comparison
8312      * @return a sorted array
8313      * @since 1.8.1
8314      */
8315     public static <T> T[] sort(T[] self, boolean mutate, Comparator<T> comparator) {
8316         T[] answer = mutate ? self : self.clone();
8317         Arrays.sort(answer, comparator);
8318         return answer;
8319     }
8320 
8321     /**
8322      * Sorts the given iterator items into a sorted iterator using the Closure to determine the correct ordering.
8323      * The original iterator will be fully processed after the method call.
8324      * <p>
8325      * If the closure has two parameters it is used like a traditional Comparator.
8326      * I.e.&#160;it should compare its two parameters for order, returning a negative integer,
8327      * zero, or a positive integer when the first parameter is less than, equal to,
8328      * or greater than the second respectively. Otherwise, the Closure is assumed
8329      * to take a single parameter and return a Comparable (typically an Integer)
8330      * which is then used for further comparison.
8331      *
8332      * @param self    the Iterator to be sorted
8333      * @param closure a Closure used to determine the correct ordering
8334      * @return the sorted items as an Iterator
8335      * @since 1.5.5
8336      */
8337     public static <T> Iterator<T> sort(Iterator<T> self, @ClosureParams(value=FromString.class, options={"T","T,T"}) Closure closure) {
8338         return sort((Iterable<T>) toList(self), closure).listIterator();
8339     }
8340 
8341     /**
8342      * Sorts the elements from this array into a newly created array using
8343      * the Closure to determine the correct ordering.
8344      * <p>
8345      * If the closure has two parameters it is used like a traditional Comparator. I.e. it should compare
8346      * its two parameters for order, returning a negative integer, zero, or a positive integer when the
8347      * first parameter is less than, equal to, or greater than the second respectively. Otherwise,
8348      * the Closure is assumed to take a single parameter and return a Comparable (typically an Integer)
8349      * which is then used for further comparison.
8350      *
8351      * @param self the array containing the elements to be sorted
8352      * @param closure a Closure used to determine the correct ordering
8353      * @return the sorted array
8354      * @since 1.5.5
8355      */
8356     @SuppressWarnings("unchecked")
8357     public static <T> T[] sort(T[] self, @ClosureParams(value=FromString.class, options={"T","T,T"}) Closure closure) {
8358         return sort(self, false, closure);
8359     }
8360 
8361     /**
8362      * Modifies this array so that its elements are in sorted order using the Closure to determine the correct ordering.
8363      * If mutate is false, a new array is returned and the original array remains unchanged.
8364      * Otherwise, the original array is sorted in place and returned.
8365      * <p>
8366      * If the closure has two parameters it is used like a traditional Comparator. I.e. it should compare
8367      * its two parameters for order, returning a negative integer, zero, or a positive integer when the
8368      * first parameter is less than, equal to, or greater than the second respectively. Otherwise,
8369      * the Closure is assumed to take a single parameter and return a Comparable (typically an Integer)
8370      * which is then used for further comparison.
8371      * <pre class="groovyTestCase">
8372      * def orig = ["hello","hi","Hey"] as String[]
8373      * def sorted = orig.sort(false) { it.size() }
8374      * assert orig == ["hello","hi","Hey"] as String[]
8375      * assert sorted == ["hi","Hey","hello"] as String[]
8376      * orig.sort(true) { it.size() }
8377      * assert orig == ["hi","Hey","hello"] as String[]
8378      * </pre>
8379      *
8380      * @param self    the array to be sorted
8381      * @param mutate  false will always cause a new array to be created, true will mutate arrays in place
8382      * @param closure a Closure used to determine the correct ordering
8383      * @return the sorted array
8384      * @since 1.8.1
8385      */
8386     @SuppressWarnings("unchecked")
8387     public static <T> T[] sort(T[] self, boolean mutate, @ClosureParams(value=FromString.class, options={"T","T,T"}) Closure closure) {
8388         T[] answer = (T[]) sort((Iterable<T>) toList(self), closure).toArray();
8389         if (mutate) {
8390             System.arraycopy(answer, 0, self, 0, answer.length);
8391         }
8392         return mutate ? self : answer;
8393     }
8394 
8395     /**
8396      * @deprecated Use the Iterable version of sort instead
8397      * @see #sort(Iterable, boolean, Closure)
8398      * @since 1.8.1
8399      */
8400     @Deprecated
8401     public static <T> List<T> sort(Collection<T> self, boolean mutate, Closure closure) {
8402         return sort((Iterable<T>)self, mutate, closure);
8403     }
8404 
8405     /**
8406      * @deprecated Use the Iterable version of sort instead
8407      * @see #sort(Iterable, Closure)
8408      * @since 1.0
8409      */
8410     @Deprecated
8411     public static <T> List<T> sort(Collection<T> self, @ClosureParams(value=FromString.class, options={"T","T,T"}) Closure closure) {
8412         return sort((Iterable<T>)self, closure);
8413     }
8414 
8415     /**
8416      * Sorts this Iterable using the given Closure to determine the correct ordering. If the Iterable is a List,
8417      * it is sorted in place and returned. Otherwise, the elements are first placed
8418      * into a new list which is then sorted and returned - leaving the original Iterable unchanged.
8419      * <p>
8420      * If the Closure has two parameters
8421      * it is used like a traditional Comparator. I.e. it should compare
8422      * its two parameters for order, returning a negative integer,
8423      * zero, or a positive integer when the first parameter is less than,
8424      * equal to, or greater than the second respectively. Otherwise,
8425      * the Closure is assumed to take a single parameter and return a
8426      * Comparable (typically an Integer) which is then used for
8427      * further comparison.
8428      * <pre class="groovyTestCase">assert ["hi","hey","hello"] == ["hello","hi","hey"].sort { it.length() }</pre>
8429      * <pre class="groovyTestCase">assert ["hi","hey","hello"] == ["hello","hi","hey"].sort { a, b -> a.length() <=> b.length() }</pre>
8430      *
8431      * @param self    the Iterable to be sorted
8432      * @param closure a 1 or 2 arg Closure used to determine the correct ordering
8433      * @return a newly created sorted List
8434      * @see #sort(Collection, boolean, Closure)
8435      * @since 2.2.0
8436      */
8437     public static <T> List<T> sort(Iterable<T> self, @ClosureParams(value=FromString.class, options={"T","T,T"}) Closure closure) {
8438         return sort(self, true, closure);
8439     }
8440 
8441     /**
8442      * Sorts this Iterable using the given Closure to determine the correct ordering. If the Iterable is a List
8443      * and mutate is true, it is sorted in place and returned. Otherwise, the elements are first placed
8444      * into a new list which is then sorted and returned - leaving the original Iterable unchanged.
8445      * <p>
8446      * If the closure has two parameters
8447      * it is used like a traditional Comparator. I.e. it should compare
8448      * its two parameters for order, returning a negative integer,
8449      * zero, or a positive integer when the first parameter is less than,
8450      * equal to, or greater than the second respectively. Otherwise,
8451      * the Closure is assumed to take a single parameter and return a
8452      * Comparable (typically an Integer) which is then used for
8453      * further comparison.
8454      * <pre class="groovyTestCase">assert ["hi","hey","hello"] == ["hello","hi","hey"].sort { it.length() }</pre>
8455      * <pre class="groovyTestCase">assert ["hi","hey","hello"] == ["hello","hi","hey"].sort { a, b -> a.length() <=> b.length() }</pre>
8456      * <pre class="groovyTestCase">
8457      * def orig = ["hello","hi","Hey"]
8458      * def sorted = orig.sort(false) { it.toUpperCase() }
8459      * assert orig == ["hello","hi","Hey"]
8460      * assert sorted == ["hello","Hey","hi"]
8461      * </pre>
8462      *
8463      * @param self    the Iterable to be sorted
8464      * @param mutate  false will always cause a new list to be created, true will mutate lists in place
8465      * @param closure a 1 or 2 arg Closure used to determine the correct ordering
8466      * @return a newly created sorted List
8467      * @since 2.2.0
8468      */
8469     public static <T> List<T> sort(Iterable<T> self, boolean mutate, Closure closure) {
8470         List<T> list = mutate ? asList(self) : toList(self);
8471         // use a comparator of one item or two
8472         int params = closure.getMaximumNumberOfParameters();
8473         if (params == 1) {
8474             Collections.sort(list, new OrderBy<T>(closure));
8475         } else {
8476             Collections.sort(list, new ClosureComparator<T>(closure));
8477         }
8478         return list;
8479     }
8480 
8481     /**
8482      * Avoids doing unnecessary work when sorting an already sorted set (i.e. an identity function for an already sorted set).
8483      *
8484      * @param self an already sorted set
8485      * @return the set
8486      * @since 1.0
8487      */
8488     public static <T> SortedSet<T> sort(SortedSet<T> self) {
8489         return self;
8490     }
8491 
8492     /**
8493      * Avoids doing unnecessary work when sorting an already sorted map (i.e. an identity function for an already sorted map).
8494      *
8495      * @param self an already sorted map
8496      * @return the map
8497      * @since 1.8.1
8498      */
8499     public static <K, V> SortedMap<K, V> sort(SortedMap<K, V> self) {
8500         return self;
8501     }
8502 
8503     /**
8504      * Sorts the Iterable. Assumes that the Iterable elements are
8505      * comparable and uses a {@link NumberAwareComparator} to determine the resulting order.
8506      * {@code NumberAwareComparator} has special treatment for numbers but otherwise uses the
8507      * natural ordering of the Iterable elements. The elements are first placed into a new list which
8508      * is then sorted and returned - leaving the original Iterable unchanged.
8509      * <pre class="groovyTestCase">
8510      * def orig = [1, 3, 2]
8511      * def sorted = orig.toSorted()
8512      * assert orig == [1, 3, 2]
8513      * assert sorted == [1, 2, 3]
8514      * </pre>
8515      *
8516      * @param self   the Iterable to be sorted
8517      * @return the sorted iterable as a List
8518      * @see #toSorted(Iterable, Comparator)
8519      * @since 2.4.0
8520      */
8521     public static <T> List<T> toSorted(Iterable<T> self) {
8522         return toSorted(self, new NumberAwareComparator<T>());
8523     }
8524 
8525     /**
8526      * Sorts the Iterable using the given Comparator. The elements are first placed
8527      * into a new list which is then sorted and returned - leaving the original Iterable unchanged.
8528      * <pre class="groovyTestCase">
8529      * def orig = ["hello","hi","Hey"]
8530      * def sorted = orig.toSorted(String.CASE_INSENSITIVE_ORDER)
8531      * assert orig == ["hello","hi","Hey"]
8532      * assert sorted == ["hello","Hey","hi"]
8533      * </pre>
8534      *
8535      * @param self       the Iterable to be sorted
8536      * @param comparator a Comparator used for the comparison
8537      * @return a sorted List
8538      * @since 2.4.0
8539      */
8540     public static <T> List<T> toSorted(Iterable<T> self, Comparator<T> comparator) {
8541         List<T> list = toList(self);
8542         Collections.sort(list, comparator);
8543         return list;
8544     }
8545 
8546     /**
8547      * Sorts this Iterable using the given Closure to determine the correct ordering. The elements are first placed
8548      * into a new list which is then sorted and returned - leaving the original Iterable unchanged.
8549      * <p>
8550      * If the Closure has two parameters
8551      * it is used like a traditional Comparator. I.e. it should compare
8552      * its two parameters for order, returning a negative integer,
8553      * zero, or a positive integer when the first parameter is less than,
8554      * equal to, or greater than the second respectively. Otherwise,
8555      * the Closure is assumed to take a single parameter and return a
8556      * Comparable (typically an Integer) which is then used for
8557      * further comparison.
8558      * <pre class="groovyTestCase">assert ["hi","hey","hello"] == ["hello","hi","hey"].sort { it.length() }</pre>
8559      * <pre class="groovyTestCase">assert ["hi","hey","hello"] == ["hello","hi","hey"].sort { a, b -> a.length() <=> b.length() }</pre>
8560      *
8561      * @param self    the Iterable to be sorted
8562      * @param closure a 1 or 2 arg Closure used to determine the correct ordering
8563      * @return a newly created sorted List
8564      * @see #toSorted(Iterable, Comparator)
8565      * @since 2.4.0
8566      */
8567     public static <T> List<T> toSorted(Iterable<T> self, @ClosureParams(value=FromString.class, options={"T","T,T"}) Closure closure) {
8568         Comparator<T> comparator = (closure.getMaximumNumberOfParameters() == 1) ? new OrderBy<T>(closure) : new ClosureComparator<T>(closure);
8569         return toSorted(self, comparator);
8570     }
8571 
8572     /**
8573      * Sorts the Iterator. Assumes that the Iterator elements are
8574      * comparable and uses a {@link NumberAwareComparator} to determine the resulting order.
8575      * {@code NumberAwareComparator} has special treatment for numbers but otherwise uses the
8576      * natural ordering of the Iterator elements.
8577      * A new iterator is produced that traverses the items in sorted order.
8578      *
8579      * @param self       the Iterator to be sorted
8580      * @return the sorted items as an Iterator
8581      * @see #toSorted(Iterator, Comparator)
8582      * @since 2.4.0
8583      */
8584     public static <T> Iterator<T> toSorted(Iterator<T> self) {
8585         return toSorted(self, new NumberAwareComparator<T>());
8586     }
8587 
8588     /**
8589      * Sorts the given iterator items using the comparator. The
8590      * original iterator will become exhausted of elements after completing this method call.
8591      * A new iterator is produced that traverses the items in sorted order.
8592      *
8593      * @param self       the Iterator to be sorted
8594      * @param comparator a Comparator used for comparing items
8595      * @return the sorted items as an Iterator
8596      * @since 2.4.0
8597      */
8598     public static <T> Iterator<T> toSorted(Iterator<T> self, Comparator<T> comparator) {
8599         return toSorted(toList(self), comparator).listIterator();
8600     }
8601 
8602     /**
8603      * Sorts the given iterator items into a sorted iterator using the Closure to determine the correct ordering.
8604      * The original iterator will be fully processed after the method call.
8605      * <p>
8606      * If the closure has two parameters it is used like a traditional Comparator.
8607      * I.e.&#160;it should compare its two parameters for order, returning a negative integer,
8608      * zero, or a positive integer when the first parameter is less than, equal to,
8609      * or greater than the second respectively. Otherwise, the Closure is assumed
8610      * to take a single parameter and return a Comparable (typically an Integer)
8611      * which is then used for further comparison.
8612      *
8613      * @param self    the Iterator to be sorted
8614      * @param closure a Closure used to determine the correct ordering
8615      * @return the sorted items as an Iterator
8616      * @see #toSorted(Iterator, Comparator)
8617      * @since 2.4.0
8618      */
8619     public static <T> Iterator<T> toSorted(Iterator<T> self, @ClosureParams(value=FromString.class, options={"T","T,T"}) Closure closure) {
8620         Comparator<T> comparator = (closure.getMaximumNumberOfParameters() == 1) ? new OrderBy<T>(closure) : new ClosureComparator<T>(closure);
8621         return toSorted(self, comparator);
8622     }
8623 
8624     /**
8625      * Returns a sorted version of the given array using the supplied comparator.
8626      *
8627      * @param self the array to be sorted
8628      * @return the sorted array
8629      * @see #toSorted(Object[], Comparator)
8630      * @since 2.4.0
8631      */
8632     public static <T> T[] toSorted(T[] self) {
8633         return toSorted(self, new NumberAwareComparator<T>());
8634     }
8635 
8636     /**
8637      * Returns a sorted version of the given array using the supplied comparator to determine the resulting order.
8638      * <pre class="groovyTestCase">
8639      * def sumDigitsComparator = [compare: { num1, num2 -> num1.toString().toList()*.toInteger().sum() <=> num2.toString().toList()*.toInteger().sum() }] as Comparator
8640      * Integer[] nums = [9, 44, 222, 7000]
8641      * def result = nums.toSorted(sumDigitsComparator)
8642      * assert result instanceof Integer[]
8643      * assert result == [222, 7000, 44, 9]
8644      * </pre>
8645      *
8646      * @param self the array to be sorted
8647      * @param comparator a Comparator used for the comparison
8648      * @return the sorted array
8649      * @since 2.4.0
8650      */
8651     public static <T> T[] toSorted(T[] self, Comparator<T> comparator) {
8652         T[] answer = self.clone();
8653         Arrays.sort(answer, comparator);
8654         return answer;
8655     }
8656 
8657     /**
8658      * Sorts the elements from this array into a newly created array using
8659      * the Closure to determine the correct ordering.
8660      * <p>
8661      * If the closure has two parameters it is used like a traditional Comparator. I.e. it should compare
8662      * its two parameters for order, returning a negative integer, zero, or a positive integer when the
8663      * first parameter is less than, equal to, or greater than the second respectively. Otherwise,
8664      * the Closure is assumed to take a single parameter and return a Comparable (typically an Integer)
8665      * which is then used for further comparison.
8666      *
8667      * @param self the array containing the elements to be sorted
8668      * @param condition a Closure used to determine the correct ordering
8669      * @return a sorted array
8670      * @see #toSorted(Object[], Comparator)
8671      * @since 2.4.0
8672      */
8673     public static <T> T[] toSorted(T[] self, @ClosureParams(value=FromString.class, options={"T","T,T"}) Closure condition) {
8674         Comparator<T> comparator = (condition.getMaximumNumberOfParameters() == 1) ? new OrderBy<T>(condition) : new ClosureComparator<T>(condition);
8675         return toSorted(self, comparator);
8676     }
8677 
8678     /**
8679      * Sorts the elements from the given map into a new ordered map using
8680      * a {@link NumberAwareComparator} on map entry values to determine the resulting order.
8681      * {@code NumberAwareComparator} has special treatment for numbers but otherwise uses the
8682      * natural ordering of the Iterator elements. The original map is unchanged.
8683      * <pre class="groovyTestCase">
8684      * def map = [a:5L, b:3, c:6, d:4.0].toSorted()
8685      * assert map.toString() == '[b:3, d:4.0, a:5, c:6]'
8686      * </pre>
8687      *
8688      * @param self the original unsorted map
8689      * @return the sorted map
8690      * @since 2.4.0
8691      */
8692     public static <K, V> Map<K, V> toSorted(Map<K, V> self) {
8693         return toSorted(self, new NumberAwareValueComparator<K, V>());
8694     }
8695 
8696     private static class NumberAwareValueComparator<K, V> implements Comparator<Map.Entry<K, V>> {
8697         private Comparator<V> delegate = new NumberAwareComparator<V>();
8698 
8699         @Override
8700         public int compare(Map.Entry<K, V> e1, Map.Entry<K, V> e2) {
8701             return delegate.compare(e1.getValue(), e2.getValue());
8702         }
8703     }
8704 
8705     /**
8706      * Sorts the elements from the given map into a new ordered map using
8707      * the supplied comparator to determine the ordering. The original map is unchanged.
8708      * <pre class="groovyTestCase">
8709      * def keyComparator = [compare: { e1, e2 -> e1.key <=> e2.key }] as Comparator
8710      * def valueComparator = [compare: { e1, e2 -> e1.value <=> e2.value }] as Comparator
8711      * def map1 = [a:5, b:3, d:4, c:6].toSorted(keyComparator)
8712      * assert map1.toString() == '[a:5, b:3, c:6, d:4]'
8713      * def map2 = [a:5, b:3, d:4, c:6].toSorted(valueComparator)
8714      * assert map2.toString() == '[b:3, d:4, a:5, c:6]'
8715      * </pre>
8716      *
8717      * @param self the original unsorted map
8718      * @param comparator a Comparator used for the comparison
8719      * @return the sorted map
8720      * @since 2.4.0
8721      */
8722     public static <K, V> Map<K, V> toSorted(Map<K, V> self, Comparator<Map.Entry<K, V>> comparator) {
8723         List<Map.Entry<K, V>> sortedEntries = toSorted(self.entrySet(), comparator);
8724         Map<K, V> result = new LinkedHashMap<K, V>();
8725         for (Map.Entry<K, V> entry : sortedEntries) {
8726             result.put(entry.getKey(), entry.getValue());
8727         }
8728         return result;
8729     }
8730 
8731     /**
8732      * Sorts the elements from the given map into a new ordered map using
8733      * the supplied Closure condition as a comparator to determine the ordering. The original map is unchanged.
8734      * <p>
8735      * If the closure has two parameters it is used like a traditional Comparator. I.e. it should compare
8736      * its two entry parameters for order, returning a negative integer, zero, or a positive integer when the
8737      * first parameter is less than, equal to, or greater than the second respectively. Otherwise,
8738      * the Closure is assumed to take a single entry parameter and return a Comparable (typically an Integer)
8739      * which is then used for further comparison.
8740      * <pre class="groovyTestCase">
8741      * def map = [a:5, b:3, c:6, d:4].toSorted { a, b -> a.value <=> b.value }
8742      * assert map.toString() == '[b:3, d:4, a:5, c:6]'
8743      * </pre>
8744      *
8745      * @param self the original unsorted map
8746      * @param condition a Closure used as a comparator
8747      * @return the sorted map
8748      * @since 2.4.0
8749      */
8750     public static <K, V> Map<K, V> toSorted(Map<K, V> self, @ClosureParams(value=FromString.class, options={"Map.Entry<K,V>","Map.Entry<K,V>,Map.Entry<K,V>"}) Closure condition) {
8751         Comparator<Map.Entry<K,V>> comparator = (condition.getMaximumNumberOfParameters() == 1) ? new OrderBy<Map.Entry<K,V>>(condition) : new ClosureComparator<Map.Entry<K,V>>(condition);
8752         return toSorted(self, comparator);
8753     }
8754 
8755     /**
8756      * Avoids doing unnecessary work when sorting an already sorted set
8757      *
8758      * @param self an already sorted set
8759      * @return an ordered copy of the sorted set
8760      * @since 2.4.0
8761      */
8762     public static <T> Set<T> toSorted(SortedSet<T> self) {
8763         return new LinkedHashSet<T>(self);
8764     }
8765 
8766     /**
8767      * Avoids doing unnecessary work when sorting an already sorted map
8768      *
8769      * @param self an already sorted map
8770      * @return an ordered copy of the map
8771      * @since 2.4.0
8772      */
8773     public static <K, V> Map<K, V> toSorted(SortedMap<K, V> self) {
8774         return new LinkedHashMap<K, V>(self);
8775     }
8776 
8777     /**
8778      * Removes the last item from the List. Using add() and pop()
8779      * is similar to push and pop on a Stack.
8780      * <pre class="groovyTestCase">def list = ["a", false, 2]
8781      * assert list.pop() == 2
8782      * assert list == ["a", false]</pre>
8783      *
8784      * @param self a List
8785      * @return the item removed from the List
8786      * @throws NoSuchElementException if the list is empty and you try to pop() it.
8787      * @since 1.0
8788      */
8789     public static <T> T pop(List<T> self) {
8790         if (self.isEmpty()) {
8791             throw new NoSuchElementException("Cannot pop() an empty List");
8792         }
8793         return self.remove(self.size() - 1);
8794     }
8795 
8796     /**
8797      * Provides an easy way to append multiple Map.Entry values to a Map.
8798      *
8799      * @param self    a Map
8800      * @param entries a Collection of Map.Entry items to be added to the Map.
8801      * @return the same map, after the items have been added to it.
8802      * @since 1.6.1
8803      */
8804     public static <K, V> Map<K, V> putAll(Map<K, V> self, Collection<Map.Entry<K, V>> entries) {
8805         for (Map.Entry<K, V> entry : entries) {
8806             self.put(entry.getKey(), entry.getValue());
8807         }
8808         return self;
8809     }
8810 
8811     /**
8812      * Returns a new <code>Map</code> containing all entries from <code>self</code> and <code>entries</code>,
8813      * giving precedence to <code>entries</code>.  Any keys appearing in both Maps
8814      * will appear in the resultant map with values from the <code>entries</code>
8815      * operand. If <code>self</code> map is one of TreeMap, LinkedHashMap, Hashtable
8816      * or Properties, the returned Map will preserve that type, otherwise a HashMap will
8817      * be returned.
8818      *
8819      * @param self    a Map
8820      * @param entries a Collection of Map.Entry items to be added to the Map.
8821      * @return a new Map containing all key, value pairs from self and entries
8822      * @since 1.6.1
8823      */
8824     public static <K, V> Map<K, V> plus(Map<K, V> self, Collection<Map.Entry<K, V>> entries) {
8825         Map<K, V> map = cloneSimilarMap(self);
8826         putAll(map, entries);
8827         return map;
8828     }
8829 
8830     /**
8831      * Appends an item to the List. Synonym for add().
8832      * <pre class="groovyTestCase">def list = [3, 4, 2]
8833      * list.push("x")
8834      * assert list == [3, 4, 2, "x"]</pre>
8835      *
8836      * @param self a List
8837      * @param value element to be appended to this list.
8838      * @return <tt>true</tt> (as per the general contract of the
8839      *            <tt>Collection.add</tt> method).
8840      * @throws NoSuchElementException if the list is empty and you try to pop() it.
8841      * @since 1.5.5
8842      */
8843     public static <T> boolean push(List<T> self, T value) {
8844         return self.add(value);
8845     }
8846 
8847     /**
8848      * Returns the last item from the List.
8849      * <pre class="groovyTestCase">
8850      * def list = [3, 4, 2]
8851      * assert list.last() == 2
8852      * // check original is unaltered
8853      * assert list == [3, 4, 2]
8854      * </pre>
8855      *
8856      * @param self a List
8857      * @return the last item from the List
8858      * @throws NoSuchElementException if the list is empty and you try to access the last() item.
8859      * @since 1.5.5
8860      */
8861     public static <T> T last(List<T> self) {
8862         if (self.isEmpty()) {
8863             throw new NoSuchElementException("Cannot access last() element from an empty List");
8864         }
8865         return self.get(self.size() - 1);
8866     }
8867 
8868     /**
8869      * Returns the last item from the Iterable.
8870      * <pre class="groovyTestCase">
8871      * def set = [3, 4, 2] as LinkedHashSet
8872      * assert set.last() == 2
8873      * // check original unaltered
8874      * assert set == [3, 4, 2] as Set
8875      * </pre>
8876      * The first element returned by the Iterable's iterator is returned.
8877      * If the Iterable doesn't guarantee a defined order it may appear like
8878      * a random element is returned.
8879      *
8880      * @param self an Iterable
8881      * @return the first item from the Iterable
8882      * @throws NoSuchElementException if the Iterable is empty and you try to access the last() item.
8883      * @since 1.8.7
8884      */
8885     public static <T> T last(Iterable<T> self) {
8886         Iterator<T> iterator = self.iterator();
8887         if (!iterator.hasNext()) {
8888             throw new NoSuchElementException("Cannot access last() element from an empty Iterable");
8889         }
8890         T result = null;
8891         while (iterator.hasNext()) {
8892             result = iterator.next();
8893         }
8894         return result;
8895     }
8896 
8897     /**
8898      * Returns the last item from the array.
8899      * <pre class="groovyTestCase">
8900      * def array = [3, 4, 2].toArray()
8901      * assert array.last() == 2
8902      * </pre>
8903      *
8904      * @param self an array
8905      * @return the last item from the array
8906      * @throws NoSuchElementException if the array is empty and you try to access the last() item.
8907      * @since 1.7.3
8908      */
8909     public static <T> T last(T[] self) {
8910         if (self.length == 0) {
8911             throw new NoSuchElementException("Cannot access last() element from an empty Array");
8912         }
8913         return self[self.length - 1];
8914     }
8915 
8916     /**
8917      * Returns the first item from the List.
8918      * <pre class="groovyTestCase">
8919      * def list = [3, 4, 2]
8920      * assert list.first() == 3
8921      * // check original is unaltered
8922      * assert list == [3, 4, 2]
8923      * </pre>
8924      *
8925      * @param self a List
8926      * @return the first item from the List
8927      * @throws NoSuchElementException if the list is empty and you try to access the first() item.
8928      * @since 1.5.5
8929      */
8930     public static <T> T first(List<T> self) {
8931         if (self.isEmpty()) {
8932             throw new NoSuchElementException("Cannot access first() element from an empty List");
8933         }
8934         return self.get(0);
8935     }
8936 
8937     /**
8938      * Returns the first item from the Iterable.
8939      * <pre class="groovyTestCase">
8940      * def set = [3, 4, 2] as LinkedHashSet
8941      * assert set.first() == 3
8942      * // check original is unaltered
8943      * assert set == [3, 4, 2] as Set
8944      * </pre>
8945      * The first element returned by the Iterable's iterator is returned.
8946      * If the Iterable doesn't guarantee a defined order it may appear like
8947      * a random element is returned.
8948      *
8949      * @param self an Iterable
8950      * @return the first item from the Iterable
8951      * @throws NoSuchElementException if the Iterable is empty and you try to access the first() item.
8952      * @since 1.8.7
8953      */
8954     public static <T> T first(Iterable<T> self) {
8955         Iterator<T> iterator = self.iterator();
8956         if (!iterator.hasNext()) {
8957             throw new NoSuchElementException("Cannot access first() element from an empty Iterable");
8958         }
8959         return iterator.next();
8960     }
8961 
8962     /**
8963      * Returns the first item from the array.
8964      * <pre class="groovyTestCase">
8965      * def array = [3, 4, 2].toArray()
8966      * assert array.first() == 3
8967      * </pre>
8968      *
8969      * @param self an array
8970      * @return the first item from the array
8971      * @throws NoSuchElementException if the array is empty and you try to access the first() item.
8972      * @since 1.7.3
8973      */
8974     public static <T> T first(T[] self) {
8975         if (self.length == 0) {
8976             throw new NoSuchElementException("Cannot access first() element from an empty array");
8977         }
8978         return self[0];
8979     }
8980 
8981     /**
8982      * Returns the first item from the Iterable.
8983      * <pre class="groovyTestCase">
8984      * def set = [3, 4, 2] as LinkedHashSet
8985      * assert set.head() == 3
8986      * // check original is unaltered
8987      * assert set == [3, 4, 2] as Set
8988      * </pre>
8989      * The first element returned by the Iterable's iterator is returned.
8990      * If the Iterable doesn't guarantee a defined order it may appear like
8991      * a random element is returned.
8992      *
8993      * @param self an Iterable
8994      * @return the first item from the Iterable
8995      * @throws NoSuchElementException if the Iterable is empty and you try to access the head() item.
8996      * @since 2.4.0
8997      */
8998     public static <T> T head(Iterable<T> self) {
8999         return first(self);
9000     }
9001 
9002     /**
9003      * Returns the first item from the List.
9004      * <pre class="groovyTestCase">def list = [3, 4, 2]
9005      * assert list.head() == 3
9006      * assert list == [3, 4, 2]</pre>
9007      *
9008      * @param self a List
9009      * @return the first item from the List
9010      * @throws NoSuchElementException if the list is empty and you try to access the head() item.
9011      * @since 1.5.5
9012      */
9013     public static <T> T head(List<T> self) {
9014         return first(self);
9015     }
9016 
9017     /**
9018      * Returns the first item from the Object array.
9019      * <pre class="groovyTestCase">def array = [3, 4, 2].toArray()
9020      * assert array.head() == 3</pre>
9021      *
9022      * @param self an array
9023      * @return the first item from the Object array
9024      * @throws NoSuchElementException if the array is empty and you try to access the head() item.
9025      * @since 1.7.3
9026      */
9027     public static <T> T head(T[] self) {
9028         return first(self);
9029     }
9030 
9031     /**
9032      * Returns the items from the List excluding the first item.
9033      * <pre class="groovyTestCase">
9034      * def list = [3, 4, 2]
9035      * assert list.tail() == [4, 2]
9036      * assert list == [3, 4, 2]
9037      * </pre>
9038      *
9039      * @param self a List
9040      * @return a List without its first element
9041      * @throws NoSuchElementException if the List is empty and you try to access the tail()
9042      * @since 1.5.6
9043      */
9044     public static <T> List<T> tail(List<T> self) {
9045         return (List<T>) tail((Iterable<T>)self);
9046     }
9047 
9048     /**
9049      * Returns the items from the SortedSet excluding the first item.
9050      * <pre class="groovyTestCase">
9051      * def sortedSet = [3, 4, 2] as SortedSet
9052      * assert sortedSet.tail() == [3, 4] as SortedSet
9053      * assert sortedSet == [3, 4, 2] as SortedSet
9054      * </pre>
9055      *
9056      * @param self an SortedSet
9057      * @return a SortedSet without its first element
9058      * @throws NoSuchElementException if the SortedSet is empty and you try to access the tail()
9059      * @since 2.4.0
9060      */
9061     public static <T> SortedSet<T> tail(SortedSet<T> self) {
9062         return (SortedSet<T>) tail((Iterable<T>) self);
9063     }
9064 
9065     /**
9066      * Returns the items from the Iterable excluding the first item.
9067      * <pre class="groovyTestCase">
9068      * def list = [3, 4, 2]
9069      * assert list.tail() == [4, 2]
9070      * assert list == [3, 4, 2]
9071      * </pre>
9072      *
9073      * @param self an Iterable
9074      * @return a collection without its first element
9075      * @throws NoSuchElementException if the iterable is empty and you try to access the tail()
9076      * @since 2.4.0
9077      */
9078     public static <T> Collection<T> tail(Iterable<T> self) {
9079         if (!self.iterator().hasNext()) {
9080             throw new NoSuchElementException("Cannot access tail() for an empty iterable");
9081         }
9082         Collection<T> result = createSimilarCollection(self);
9083         addAll(result, tail(self.iterator()));
9084         return result;
9085     }
9086 
9087     /**
9088      * Returns the items from the array excluding the first item.
9089      * <pre class="groovyTestCase">
9090      * String[] strings = ["a", "b", "c"]
9091      * def result = strings.tail()
9092      * assert result.class.componentType == String
9093      * String[] expected = ["b", "c"]
9094      * assert result == expected
9095      * </pre>
9096      *
9097      * @param self an array
9098      * @return an array without its first element
9099      * @throws NoSuchElementException if the array is empty and you try to access the tail()
9100      * @since 1.7.3
9101      */
9102     @SuppressWarnings("unchecked")
9103     public static <T> T[] tail(T[] self) {
9104         if (self.length == 0) {
9105             throw new NoSuchElementException("Cannot access tail() for an empty array");
9106         }
9107         T[] result = createSimilarArray(self, self.length - 1);
9108         System.arraycopy(self, 1, result, 0, self.length - 1);
9109         return result;
9110     }
9111 
9112     /**
9113      * Returns the original iterator after throwing away the first element.
9114      *
9115      * @param self the original iterator
9116      * @return the iterator without its first element
9117      * @throws NoSuchElementException if the array is empty and you try to access the tail()
9118      * @since 1.8.1
9119      */
9120     public static <T> Iterator<T> tail(Iterator<T> self) {
9121         if (!self.hasNext()) {
9122             throw new NoSuchElementException("Cannot access tail() for an empty Iterator");
9123         }
9124         self.next();
9125         return self;
9126     }
9127 
9128     /**
9129      * Returns the items from the Iterable excluding the last item. Leaves the original Iterable unchanged.
9130      * <pre class="groovyTestCase">
9131      * def list = [3, 4, 2]
9132      * assert list.init() == [3, 4]
9133      * assert list == [3, 4, 2]
9134      * </pre>
9135      *
9136      * @param self an Iterable
9137      * @return a Collection without its last element
9138      * @throws NoSuchElementException if the iterable is empty and you try to access init()
9139      * @since 2.4.0
9140      */
9141     public static <T> Collection<T> init(Iterable<T> self) {
9142         if (!self.iterator().hasNext()) {
9143             throw new NoSuchElementException("Cannot access init() for an empty Iterable");
9144         }
9145         Collection<T> result;
9146         if (self instanceof Collection) {
9147             Collection<T> selfCol = (Collection<T>) self;
9148             result = createSimilarCollection(selfCol, selfCol.size() - 1);
9149         } else {
9150             result = new ArrayList<T>();
9151         }
9152         addAll(result, init(self.iterator()));
9153         return result;
9154     }
9155 
9156     /**
9157      * Returns the items from the List excluding the last item. Leaves the original List unchanged.
9158      * <pre class="groovyTestCase">
9159      * def list = [3, 4, 2]
9160      * assert list.init() == [3, 4]
9161      * assert list == [3, 4, 2]
9162      * </pre>
9163      *
9164      * @param self a List
9165      * @return a List without its last element
9166      * @throws NoSuchElementException if the List is empty and you try to access init()
9167      * @since 2.4.0
9168      */
9169     public static <T> List<T> init(List<T> self) {
9170         return (List<T>) init((Iterable<T>) self);
9171     }
9172 
9173     /**
9174      * Returns the items from the SortedSet excluding the last item. Leaves the original SortedSet unchanged.
9175      * <pre class="groovyTestCase">
9176      * def sortedSet = [3, 4, 2] as SortedSet
9177      * assert sortedSet.init() == [3, 4] as SortedSet
9178      * assert sortedSet == [3, 4, 2] as SortedSet
9179      * </pre>
9180      *
9181      * @param self an SortedSet
9182      * @return a SortedSet without its last element
9183      * @throws NoSuchElementException if the SortedSet is empty and you try to access init()
9184      * @since 2.4.0
9185      */
9186     public static <T> SortedSet<T> init(SortedSet<T> self) {
9187         return (SortedSet<T>) init((Iterable<T>) self);
9188     }
9189 
9190     /**
9191      * Returns an Iterator containing all of the items from this iterator except the last one.
9192      * <pre class="groovyTestCase">
9193      * def iter = [3, 4, 2].listIterator()
9194      * def result = iter.init()
9195      * assert result.toList() == [3, 4]
9196      * </pre>
9197      *
9198      * @param self an Iterator
9199      * @return an Iterator without the last element from the original Iterator
9200      * @throws NoSuchElementException if the iterator is empty and you try to access init()
9201      * @since 2.4.0
9202      */
9203     public static <T> Iterator<T> init(Iterator<T> self) {
9204         if (!self.hasNext()) {
9205             throw new NoSuchElementException("Cannot access init() for an empty Iterator");
9206         }
9207         return new InitIterator<T>(self);
9208     }
9209 
9210     private static final class InitIterator<E> implements Iterator<E> {
9211         private final Iterator<E> delegate;
9212         private boolean exhausted;
9213         private E next;
9214 
9215         private InitIterator(Iterator<E> delegate) {
9216             this.delegate = delegate;
9217             advance();
9218         }
9219 
9220         public boolean hasNext() {
9221             return !exhausted;
9222         }
9223 
9224         public E next() {
9225             if (exhausted) throw new NoSuchElementException();
9226             E result = next;
9227             advance();
9228             return result;
9229         }
9230 
9231         public void remove() {
9232             if (exhausted) throw new NoSuchElementException();
9233             advance();
9234         }
9235 
9236         private void advance() {
9237             next = delegate.next();
9238             exhausted = !delegate.hasNext();
9239         }
9240     }
9241 
9242     /**
9243      * Returns the items from the Object array excluding the last item.
9244      * <pre class="groovyTestCase">
9245      *     String[] strings = ["a", "b", "c"]
9246      *     def result = strings.init()
9247      *     assert result.length == 2
9248      *     assert strings.class.componentType == String
9249      * </pre>
9250      *
9251      * @param self an array
9252      * @return an array without its last element
9253      * @throws NoSuchElementException if the array is empty and you try to access the init() item.
9254      * @since 2.4.0
9255      */
9256     public static <T> T[] init(T[] self) {
9257         if (self.length == 0) {
9258             throw new NoSuchElementException("Cannot access init() for an empty Object array");
9259         }
9260         T[] result = createSimilarArray(self, self.length - 1);
9261         System.arraycopy(self, 0, result, 0, self.length - 1);
9262         return result;
9263     }
9264 
9265     /**
9266      * Returns the first <code>num</code> elements from the head of this List.
9267      * <pre class="groovyTestCase">
9268      * def strings = [ 'a', 'b', 'c' ]
9269      * assert strings.take( 0 ) == []
9270      * assert strings.take( 2 ) == [ 'a', 'b' ]
9271      * assert strings.take( 5 ) == [ 'a', 'b', 'c' ]
9272      * </pre>
9273      *
9274      * @param self the original List
9275      * @param num  the number of elements to take from this List
9276      * @return a List consisting of the first <code>num</code> elements from this List,
9277      *         or else all the elements from the List if it has less then <code>num</code> elements.
9278      * @since 1.8.1
9279      */
9280     public static <T> List<T> take(List<T> self, int num) {
9281         return (List<T>) take((Iterable<T>)self, num);
9282     }
9283 
9284     /**
9285      * Returns the first <code>num</code> elements from the head of this SortedSet.
9286      * <pre class="groovyTestCase">
9287      * def strings = [ 'a', 'b', 'c' ] as SortedSet
9288      * assert strings.take( 0 ) == [] as SortedSet
9289      * assert strings.take( 2 ) == [ 'a', 'b' ] as SortedSet
9290      * assert strings.take( 5 ) == [ 'a', 'b', 'c' ] as SortedSet
9291      * </pre>
9292      *
9293      * @param self the original SortedSet
9294      * @param num  the number of elements to take from this SortedSet
9295      * @return a SortedSet consisting of the first <code>num</code> elements from this List,
9296      *         or else all the elements from the SortedSet if it has less then <code>num</code> elements.
9297      * @since 2.4.0
9298      */
9299     public static <T> SortedSet<T> take(SortedSet<T> self, int num) {
9300         return (SortedSet<T>) take((Iterable<T>) self, num);
9301     }
9302 
9303     /**
9304      * Returns the first <code>num</code> elements from the head of this array.
9305      * <pre class="groovyTestCase">
9306      * String[] strings = [ 'a', 'b', 'c' ]
9307      * assert strings.take( 0 ) == [] as String[]
9308      * assert strings.take( 2 ) == [ 'a', 'b' ] as String[]
9309      * assert strings.take( 5 ) == [ 'a', 'b', 'c' ] as String[]
9310      * </pre>
9311      *
9312      * @param self the original array
9313      * @param num  the number of elements to take from this array
9314      * @return an array consisting of the first <code>num</code> elements of this array,
9315      *         or else the whole array if it has less then <code>num</code> elements.
9316      * @since 1.8.1
9317      */
9318     public static <T> T[] take(T[] self, int num) {
9319         if (self.length == 0 || num <= 0) {
9320             return createSimilarArray(self, 0);
9321         }
9322 
9323         if (self.length <= num) {
9324             T[] ret = createSimilarArray(self, self.length);
9325             System.arraycopy(self, 0, ret, 0, self.length);
9326             return ret;
9327         }
9328 
9329         T[] ret = createSimilarArray(self, num);
9330         System.arraycopy(self, 0, ret, 0, num);
9331         return ret;
9332     }
9333 
9334     /**
9335      * Returns the first <code>num</code> elements from the head of this Iterable.
9336      * <pre class="groovyTestCase">
9337      * def strings = [ 'a', 'b', 'c' ]
9338      * assert strings.take( 0 ) == []
9339      * assert strings.take( 2 ) == [ 'a', 'b' ]
9340      * assert strings.take( 5 ) == [ 'a', 'b', 'c' ]
9341      *
9342      * class AbcIterable implements Iterable<String> {
9343      *     Iterator<String> iterator() { "abc".iterator() }
9344      * }
9345      * def abc = new AbcIterable()
9346      * assert abc.take(0) == []
9347      * assert abc.take(1) == ['a']
9348      * assert abc.take(3) == ['a', 'b', 'c']
9349      * assert abc.take(5) == ['a', 'b', 'c']
9350      * </pre>
9351      *
9352      * @param self the original Iterable
9353      * @param num  the number of elements to take from this Iterable
9354      * @return a Collection consisting of the first <code>num</code> elements from this Iterable,
9355      *         or else all the elements from the Iterable if it has less then <code>num</code> elements.
9356      * @since 1.8.7
9357      */
9358     public static <T> Collection<T> take(Iterable<T> self, int num) {
9359         Collection<T> result = self instanceof Collection ? createSimilarCollection((Collection<T>) self, num < 0 ? 0 : num) : new ArrayList<T>();
9360         addAll(result, take(self.iterator(), num));
9361         return result;
9362     }
9363 
9364     /**
9365      * Adds all items from the iterator to the Collection.
9366      *
9367      * @param self the collection
9368      * @param items the items to add
9369      * @return true if the collection changed
9370      */
9371     public static <T> boolean addAll(Collection<T> self, Iterator<T> items) {
9372         boolean changed = false;
9373         while (items.hasNext()) {
9374             T next =  items.next();
9375             if (self.add(next)) changed = true;
9376         }
9377         return changed;
9378     }
9379 
9380     /**
9381      * Adds all items from the iterable to the Collection.
9382      *
9383      * @param self the collection
9384      * @param items the items to add
9385      * @return true if the collection changed
9386      */
9387     public static <T> boolean addAll(Collection<T> self, Iterable<T> items) {
9388         boolean changed = false;
9389         for (T next : items) {
9390             if (self.add(next)) changed = true;
9391         }
9392         return changed;
9393     }
9394 
9395     /**
9396      * Returns a new map containing the first <code>num</code> elements from the head of this map.
9397      * If the map instance does not have ordered keys, then this function could return a random <code>num</code>
9398      * entries. Groovy by default uses LinkedHashMap, so this shouldn't be an issue in the main.
9399      * <pre class="groovyTestCase">
9400      * def strings = [ 'a':10, 'b':20, 'c':30 ]
9401      * assert strings.take( 0 ) == [:]
9402      * assert strings.take( 2 ) == [ 'a':10, 'b':20 ]
9403      * assert strings.take( 5 ) == [ 'a':10, 'b':20, 'c':30 ]
9404      * </pre>
9405      *
9406      * @param self the original map
9407      * @param num  the number of elements to take from this map
9408      * @return a new map consisting of the first <code>num</code> elements of this map,
9409      *         or else the whole map if it has less then <code>num</code> elements.
9410      * @since 1.8.1
9411      */
9412     public static <K, V> Map<K, V> take(Map<K, V> self, int num) {
9413         if (self.isEmpty() || num <= 0) {
9414             return createSimilarMap(self);
9415         }
9416         Map<K, V> ret = createSimilarMap(self);
9417         for (K key : self.keySet()) {
9418             ret.put(key, self.get(key));
9419             if (--num <= 0) {
9420                 break;
9421             }
9422         }
9423         return ret;
9424     }
9425 
9426     /**
9427      * Returns an iterator of up to the first <code>num</code> elements from this iterator.
9428      * The original iterator is stepped along by <code>num</code> elements.
9429      * <pre class="groovyTestCase">
9430      * def a = 0
9431      * def iter = [ hasNext:{ true }, next:{ a++ } ] as Iterator
9432      * def iteratorCompare( Iterator a, List b ) {
9433      *     a.collect { it } == b
9434      * }
9435      * assert iteratorCompare( iter.take( 0 ), [] )
9436      * assert iteratorCompare( iter.take( 2 ), [ 0, 1 ] )
9437      * assert iteratorCompare( iter.take( 5 ), [ 2, 3, 4, 5, 6 ] )
9438      * </pre>
9439      *
9440      * @param self the Iterator
9441      * @param num  the number of elements to take from this iterator
9442      * @return an iterator consisting of up to the first <code>num</code> elements of this iterator.
9443      * @since 1.8.1
9444      */
9445     public static <T> Iterator<T> take(Iterator<T> self, int num) {
9446         return new TakeIterator<T>(self, num);
9447     }
9448 
9449     private static final class TakeIterator<E> implements Iterator<E> {
9450         private final Iterator<E> delegate;
9451         private Integer num;
9452 
9453         private TakeIterator(Iterator<E> delegate, Integer num) {
9454             this.delegate = delegate;
9455             this.num = num;
9456         }
9457 
9458         public boolean hasNext() {
9459             return delegate.hasNext() && num > 0;
9460         }
9461 
9462         public E next() {
9463             if (num <= 0) throw new NoSuchElementException();
9464             num--;
9465             return delegate.next();
9466         }
9467 
9468         public void remove() {
9469             delegate.remove();
9470         }
9471     }
9472 
9473     @Deprecated
9474     public static CharSequence take(CharSequence self, int num) {
9475         return StringGroovyMethods.take(self, num);
9476     }
9477 
9478     /**
9479      * Returns the last <code>num</code> elements from the tail of this array.
9480      * <pre class="groovyTestCase">
9481      * String[] strings = [ 'a', 'b', 'c' ]
9482      * assert strings.takeRight( 0 ) == [] as String[]
9483      * assert strings.takeRight( 2 ) == [ 'b', 'c' ] as String[]
9484      * assert strings.takeRight( 5 ) == [ 'a', 'b', 'c' ] as String[]
9485      * </pre>
9486      *
9487      * @param self the original array
9488      * @param num  the number of elements to take from this array
9489      * @return an array consisting of the last <code>num</code> elements of this array,
9490      *         or else the whole array if it has less then <code>num</code> elements.
9491      * @since 2.4.0
9492      */
9493     public static <T> T[] takeRight(T[] self, int num) {
9494         if (self.length == 0 || num <= 0) {
9495             return createSimilarArray(self, 0);
9496         }
9497 
9498         if (self.length <= num) {
9499             T[] ret = createSimilarArray(self, self.length);
9500             System.arraycopy(self, 0, ret, 0, self.length);
9501             return ret;
9502         }
9503 
9504         T[] ret = createSimilarArray(self, num);
9505         System.arraycopy(self, self.length - num, ret, 0, num);
9506         return ret;
9507     }
9508 
9509     /**
9510      * Returns the last <code>num</code> elements from the tail of this Iterable.
9511      * <pre class="groovyTestCase">
9512      * def strings = [ 'a', 'b', 'c' ]
9513      * assert strings.takeRight( 0 ) == []
9514      * assert strings.takeRight( 2 ) == [ 'b', 'c' ]
9515      * assert strings.takeRight( 5 ) == [ 'a', 'b', 'c' ]
9516      *
9517      * class AbcIterable implements Iterable<String> {
9518      *     Iterator<String> iterator() { "abc".iterator() }
9519      * }
9520      * def abc = new AbcIterable()
9521      * assert abc.takeRight(0) == []
9522      * assert abc.takeRight(1) == ['c']
9523      * assert abc.takeRight(3) == ['a', 'b', 'c']
9524      * assert abc.takeRight(5) == ['a', 'b', 'c']
9525      * </pre>
9526      *
9527      * @param self the original Iterable
9528      * @param num  the number of elements to take from this Iterable
9529      * @return a Collection consisting of the last <code>num</code> elements from this Iterable,
9530      *         or else all the elements from the Iterable if it has less then <code>num</code> elements.
9531      * @since 2.4.0
9532      */
9533     public static <T> Collection<T> takeRight(Iterable<T> self, int num) {
9534         if (!self.iterator().hasNext() || num <= 0) {
9535             return self instanceof Collection ? createSimilarCollection((Collection<T>) self, 0) : new ArrayList<T>();
9536         }
9537         Collection<T> selfCol = self instanceof Collection ? (Collection<T>) self : toList(self);
9538         if (selfCol.size() <= num) {
9539             Collection<T> ret = createSimilarCollection(selfCol, selfCol.size());
9540             ret.addAll(selfCol);
9541             return ret;
9542         }
9543         Collection<T> ret = createSimilarCollection(selfCol, num);
9544         ret.addAll(asList((Iterable<T>) selfCol).subList(selfCol.size() - num, selfCol.size()));
9545         return ret;
9546     }
9547 
9548     /**
9549      * Returns the last <code>num</code> elements from the tail of this List.
9550      * <pre class="groovyTestCase">
9551      * def strings = [ 'a', 'b', 'c' ]
9552      * assert strings.takeRight( 0 ) == []
9553      * assert strings.takeRight( 2 ) == [ 'b', 'c' ]
9554      * assert strings.takeRight( 5 ) == [ 'a', 'b', 'c' ]
9555      * </pre>
9556      *
9557      * @param self the original List
9558      * @param num  the number of elements to take from this List
9559      * @return a List consisting of the last <code>num</code> elements from this List,
9560      *         or else all the elements from the List if it has less then <code>num</code> elements.
9561      * @since 2.4.0
9562      */
9563     public static <T> List<T> takeRight(List<T> self, int num) {
9564         return (List<T>) takeRight((Iterable<T>) self, num);
9565     }
9566 
9567     /**
9568      * Returns the last <code>num</code> elements from the tail of this SortedSet.
9569      * <pre class="groovyTestCase">
9570      * def strings = [ 'a', 'b', 'c' ] as SortedSet
9571      * assert strings.takeRight( 0 ) == [] as SortedSet
9572      * assert strings.takeRight( 2 ) == [ 'b', 'c' ] as SortedSet
9573      * assert strings.takeRight( 5 ) == [ 'a', 'b', 'c' ] as SortedSet
9574      * </pre>
9575      *
9576      * @param self the original SortedSet
9577      * @param num  the number of elements to take from this SortedSet
9578      * @return a SortedSet consisting of the last <code>num</code> elements from this SortedSet,
9579      *         or else all the elements from the SortedSet if it has less then <code>num</code> elements.
9580      * @since 2.4.0
9581      */
9582     public static <T> SortedSet<T> takeRight(SortedSet<T> self, int num) {
9583         return (SortedSet<T>) takeRight((Iterable<T>) self, num);
9584     }
9585 
9586     /**
9587      * Drops the given number of elements from the head of this List.
9588      * <pre class="groovyTestCase">
9589      * def strings = [ 'a', 'b', 'c' ] as SortedSet
9590      * assert strings.drop( 0 ) == [ 'a', 'b', 'c' ] as SortedSet
9591      * assert strings.drop( 2 ) == [ 'c' ] as SortedSet
9592      * assert strings.drop( 5 ) == [] as SortedSet
9593      * </pre>
9594      *
9595      * @param self the original SortedSet
9596      * @param num  the number of elements to drop from this Iterable
9597      * @return a SortedSet consisting of all the elements of this Iterable minus the first <code>num</code> elements,
9598      *         or an empty list if it has less then <code>num</code> elements.
9599      * @since 2.4.0
9600      */
9601     public static <T> SortedSet<T> drop(SortedSet<T> self, int num) {
9602         return (SortedSet<T>) drop((Iterable<T>) self, num);
9603     }
9604 
9605     /**
9606      * Drops the given number of elements from the head of this List.
9607      * <pre class="groovyTestCase">
9608      * def strings = [ 'a', 'b', 'c' ]
9609      * assert strings.drop( 0 ) == [ 'a', 'b', 'c' ]
9610      * assert strings.drop( 2 ) == [ 'c' ]
9611      * assert strings.drop( 5 ) == []
9612      * </pre>
9613      *
9614      * @param self the original List
9615      * @param num  the number of elements to drop from this Iterable
9616      * @return a List consisting of all the elements of this Iterable minus the first <code>num</code> elements,
9617      *         or an empty list if it has less then <code>num</code> elements.
9618      * @since 1.8.1
9619      */
9620     public static <T> List<T> drop(List<T> self, int num) {
9621         return (List<T>) drop((Iterable<T>) self, num);
9622     }
9623 
9624     /**
9625      * Drops the given number of elements from the head of this Iterable.
9626      * <pre class="groovyTestCase">
9627      * def strings = [ 'a', 'b', 'c' ]
9628      * assert strings.drop( 0 ) == [ 'a', 'b', 'c' ]
9629      * assert strings.drop( 2 ) == [ 'c' ]
9630      * assert strings.drop( 5 ) == []
9631      *
9632      * class AbcIterable implements Iterable<String> {
9633      *     Iterator<String> iterator() { "abc".iterator() }
9634      * }
9635      * def abc = new AbcIterable()
9636      * assert abc.drop(0) == ['a', 'b', 'c']
9637      * assert abc.drop(1) == ['b', 'c']
9638      * assert abc.drop(3) == []
9639      * assert abc.drop(5) == []
9640      * </pre>
9641      *
9642      * @param self the original Iterable
9643      * @param num  the number of elements to drop from this Iterable
9644      * @return a Collection consisting of all the elements of this Iterable minus the first <code>num</code> elements,
9645      *         or an empty list if it has less then <code>num</code> elements.
9646      * @since 1.8.7
9647      */
9648     public static <T> Collection<T> drop(Iterable<T> self, int num) {
9649         Collection<T> result = createSimilarCollection(self);
9650         addAll(result, drop(self.iterator(), num));
9651         return result;
9652     }
9653 
9654     /**
9655      * Drops the given number of elements from the head of this array
9656      * if they are available.
9657      * <pre class="groovyTestCase">
9658      * String[] strings = [ 'a', 'b', 'c' ]
9659      * assert strings.drop( 0 ) == [ 'a', 'b', 'c' ] as String[]
9660      * assert strings.drop( 2 ) == [ 'c' ] as String[]
9661      * assert strings.drop( 5 ) == [] as String[]
9662      * </pre>
9663      *
9664      * @param self the original array
9665      * @param num  the number of elements to drop from this array
9666      * @return an array consisting of all elements of this array except the
9667      *         first <code>num</code> ones, or else the empty array, if this
9668      *         array has less than <code>num</code> elements.
9669      * @since 1.8.1
9670      */
9671     public static <T> T[] drop(T[] self, int num) {
9672         if (self.length <= num) {
9673             return createSimilarArray(self, 0);
9674         }
9675         if (num <= 0) {
9676             T[] ret = createSimilarArray(self, self.length);
9677             System.arraycopy(self, 0, ret, 0, self.length);
9678             return ret;
9679         }
9680 
9681         T[] ret = createSimilarArray(self, self.length - num);
9682         System.arraycopy(self, num, ret, 0, self.length - num);
9683         return ret;
9684     }
9685 
9686     /**
9687      * Drops the given number of key/value pairs from the head of this map if they are available.
9688      * <pre class="groovyTestCase">
9689      * def strings = [ 'a':10, 'b':20, 'c':30 ]
9690      * assert strings.drop( 0 ) == [ 'a':10, 'b':20, 'c':30 ]
9691      * assert strings.drop( 2 ) == [ 'c':30 ]
9692      * assert strings.drop( 5 ) == [:]
9693      * </pre>
9694      * If the map instance does not have ordered keys, then this function could drop a random <code>num</code>
9695      * entries. Groovy by default uses LinkedHashMap, so this shouldn't be an issue in the main.
9696      *
9697      * @param self the original map
9698      * @param num  the number of elements to drop from this map
9699      * @return a map consisting of all key/value pairs of this map except the first
9700      *         <code>num</code> ones, or else the empty map, if this map has
9701      *         less than <code>num</code> elements.
9702      * @since 1.8.1
9703      */
9704     public static <K, V> Map<K, V> drop(Map<K, V> self, int num) {
9705         if (self.size() <= num) {
9706             return createSimilarMap(self);
9707         }
9708         if (num == 0) {
9709             return cloneSimilarMap(self);
9710         }
9711         Map<K, V> ret = createSimilarMap(self);
9712         for (K key : self.keySet()) {
9713             if (num-- <= 0) {
9714                 ret.put(key, self.get(key));
9715             }
9716         }
9717         return ret;
9718     }
9719 
9720     /**
9721      * Drops the given number of elements from the head of this iterator if they are available.
9722      * The original iterator is stepped along by <code>num</code> elements.
9723      * <pre class="groovyTestCase">
9724      * def iteratorCompare( Iterator a, List b ) {
9725      *     a.collect { it } == b
9726      * }
9727      * def iter = [ 1, 2, 3, 4, 5 ].listIterator()
9728      * assert iteratorCompare( iter.drop( 0 ), [ 1, 2, 3, 4, 5 ] )
9729      * iter = [ 1, 2, 3, 4, 5 ].listIterator()
9730      * assert iteratorCompare( iter.drop( 2 ), [ 3, 4, 5 ] )
9731      * iter = [ 1, 2, 3, 4, 5 ].listIterator()
9732      * assert iteratorCompare( iter.drop( 5 ), [] )
9733      * </pre>
9734      *
9735      * @param self the original iterator
9736      * @param num  the number of elements to drop from this iterator
9737      * @return The iterator stepped along by <code>num</code> elements if they exist.
9738      * @since 1.8.1
9739      */
9740     public static <T> Iterator<T> drop(Iterator<T> self, int num) {
9741         while (num-- > 0 && self.hasNext()) {
9742             self.next();
9743         }
9744         return self;
9745     }
9746 
9747     /**
9748      * Drops the given number of elements from the tail of this SortedSet.
9749      * <pre class="groovyTestCase">
9750      * def strings = [ 'a', 'b', 'c' ] as SortedSet
9751      * assert strings.dropRight( 0 ) == [ 'a', 'b', 'c' ] as SortedSet
9752      * assert strings.dropRight( 2 ) == [ 'a' ] as SortedSet
9753      * assert strings.dropRight( 5 ) == [] as SortedSet
9754      * </pre>
9755      *
9756      * @param self the original SortedSet
9757      * @param num  the number of elements to drop from this SortedSet
9758      * @return a List consisting of all the elements of this SortedSet minus the last <code>num</code> elements,
9759      *         or an empty SortedSet if it has less then <code>num</code> elements.
9760      * @since 2.4.0
9761      */
9762     public static <T> SortedSet<T> dropRight(SortedSet<T> self, int num) {
9763         return (SortedSet<T>) dropRight((Iterable<T>) self, num);
9764     }
9765 
9766     /**
9767      * Drops the given number of elements from the tail of this List.
9768      * <pre class="groovyTestCase">
9769      * def strings = [ 'a', 'b', 'c' ]
9770      * assert strings.dropRight( 0 ) == [ 'a', 'b', 'c' ]
9771      * assert strings.dropRight( 2 ) == [ 'a' ]
9772      * assert strings.dropRight( 5 ) == []
9773      * </pre>
9774      *
9775      * @param self the original List
9776      * @param num  the number of elements to drop from this List
9777      * @return a List consisting of all the elements of this List minus the last <code>num</code> elements,
9778      *         or an empty List if it has less then <code>num</code> elements.
9779      * @since 2.4.0
9780      */
9781     public static <T> List<T> dropRight(List<T> self, int num) {
9782         return (List<T>) dropRight((Iterable<T>) self, num);
9783     }
9784 
9785     /**
9786      * Drops the given number of elements from the tail of this Iterable.
9787      * <pre class="groovyTestCase">
9788      * def strings = [ 'a', 'b', 'c' ]
9789      * assert strings.dropRight( 0 ) == [ 'a', 'b', 'c' ]
9790      * assert strings.dropRight( 2 ) == [ 'a' ]
9791      * assert strings.dropRight( 5 ) == []
9792      *
9793      * class AbcIterable implements Iterable<String> {
9794      *     Iterator<String> iterator() { "abc".iterator() }
9795      * }
9796      * def abc = new AbcIterable()
9797      * assert abc.dropRight(0) == ['a', 'b', 'c']
9798      * assert abc.dropRight(1) == ['a', 'b']
9799      * assert abc.dropRight(3) == []
9800      * assert abc.dropRight(5) == []
9801      * </pre>
9802      *
9803      * @param self the original Iterable
9804      * @param num  the number of elements to drop from this Iterable
9805      * @return a Collection consisting of all the elements of this Iterable minus the last <code>num</code> elements,
9806      *         or an empty list if it has less then <code>num</code> elements.
9807      * @since 2.4.0
9808      */
9809     public static <T> Collection<T> dropRight(Iterable<T> self, int num) {
9810         Collection<T> selfCol = self instanceof Collection ? (Collection<T>) self : toList(self);
9811         if (selfCol.size() <= num) {
9812             return createSimilarCollection(selfCol, 0);
9813         }
9814         if (num <= 0) {
9815             Collection<T> ret = createSimilarCollection(selfCol, selfCol.size());
9816             ret.addAll(selfCol);
9817             return ret;
9818         }
9819         Collection<T> ret = createSimilarCollection(selfCol, selfCol.size() - num);
9820         ret.addAll(asList((Iterable<T>)selfCol).subList(0, selfCol.size() - num));
9821         return ret;
9822     }
9823 
9824     /**
9825      * Drops the given number of elements from the tail of this Iterator.
9826      * <pre class="groovyTestCase">
9827      * def obliterator = "obliter8".iterator()
9828      * assert abc.dropRight(-1) == ['o', 'b', 'l', 'i', 't', 'e', 'r', '8']
9829      * assert abc.dropRight(0) == ['o', 'b', 'l', 'i', 't', 'e', 'r', '8']
9830      * assert abc.dropRight(1) == ['o', 'b', 'l', 'i', 't', 'e', 'r']
9831      * assert abc.dropRight(4) == ['o', 'b', 'l', 'i']
9832      * assert abc.dropRight(7) == ['o']
9833      * assert abc.dropRight(8) == []
9834      * assert abc.dropRight(9) == []
9835      * </pre>
9836      *
9837      * @param self the original Iterator
9838      * @param num  the number of elements to drop
9839      * @return an Iterator consisting of all the elements of this Iterator minus the last <code>num</code> elements,
9840      *         or an empty Iterator if it has less then <code>num</code> elements.
9841      * @since 2.4.0
9842      */
9843     public static <T> Iterator<T> dropRight(Iterator<T> self, int num) {
9844         List<T> result = dropRight(toList(self), num);
9845         return result.listIterator();
9846     }
9847 
9848     /**
9849      * Drops the given number of elements from the tail of this array
9850      * if they are available.
9851      * <pre class="groovyTestCase">
9852      * String[] strings = [ 'a', 'b', 'c' ]
9853      * assert strings.dropRight( 0 ) == [ 'a', 'b', 'c' ] as String[]
9854      * assert strings.dropRight( 2 ) == [ 'a' ] as String[]
9855      * assert strings.dropRight( 5 ) == [] as String[]
9856      * </pre>
9857      *
9858      * @param self the original array
9859      * @param num  the number of elements to drop from this array
9860      * @return an array consisting of all elements of this array except the
9861      *         last <code>num</code> ones, or else the empty array, if this
9862      *         array has less than <code>num</code> elements.
9863      * @since 2.4.0
9864      */
9865     public static <T> T[] dropRight(T[] self, int num) {
9866         if (self.length <= num) {
9867             return createSimilarArray(self, 0);
9868         }
9869         if (num <= 0) {
9870             T[] ret = createSimilarArray(self, self.length);
9871             System.arraycopy(self, 0, ret, 0, self.length);
9872             return ret;
9873         }
9874 
9875         T[] ret = createSimilarArray(self, self.length - num);
9876         System.arraycopy(self, 0, ret, 0, self.length - num);
9877         return ret;
9878     }
9879 
9880     /**
9881      * Returns the longest prefix of this list where each element
9882      * passed to the given closure condition evaluates to true.
9883      * Similar to {@link #takeWhile(Iterable, groovy.lang.Closure)}
9884      * except that it attempts to preserve the type of the original list.
9885      * <pre class="groovyTestCase">
9886      * def nums = [ 1, 3, 2 ]
9887      * assert nums.takeWhile{ it < 1 } == []
9888      * assert nums.takeWhile{ it < 3 } == [ 1 ]
9889      * assert nums.takeWhile{ it < 4 } == [ 1, 3, 2 ]
9890      * </pre>
9891      *
9892      * @param self      the original list
9893      * @param condition the closure that must evaluate to true to
9894      *                  continue taking elements
9895      * @return a prefix of the given list where each element passed to
9896      *         the given closure evaluates to true
9897      * @since 1.8.7
9898      */
9899     public static <T> List<T> takeWhile(List<T> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure condition) {
9900         int num = 0;
9901         BooleanClosureWrapper bcw = new BooleanClosureWrapper(condition);
9902         for (T value : self) {
9903             if (bcw.call(value)) {
9904                 num += 1;
9905             } else {
9906                 break;
9907             }
9908         }
9909         return take(self, num);
9910     }
9911 
9912     /**
9913      * Returns a Collection containing the longest prefix of the elements from this Iterable
9914      * where each element passed to the given closure evaluates to true.
9915      * <pre class="groovyTestCase">
9916      * class AbcIterable implements Iterable<String> {
9917      *     Iterator<String> iterator() { "abc".iterator() }
9918      * }
9919      * def abc = new AbcIterable()
9920      * assert abc.takeWhile{ it < 'b' } == ['a']
9921      * assert abc.takeWhile{ it <= 'b' } == ['a', 'b']
9922      * </pre>
9923      *
9924      * @param self      an Iterable
9925      * @param condition the closure that must evaluate to true to
9926      *                  continue taking elements
9927      * @return a Collection containing a prefix of the elements from the given Iterable where
9928      *         each element passed to the given closure evaluates to true
9929      * @since 1.8.7
9930      */
9931     public static <T> Collection<T> takeWhile(Iterable<T> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure condition) {
9932         Collection<T> result = createSimilarCollection(self);
9933         addAll(result, takeWhile(self.iterator(), condition));
9934         return result;
9935     }
9936 
9937     /**
9938      * Returns the longest prefix of this SortedSet where each element
9939      * passed to the given closure condition evaluates to true.
9940      * Similar to {@link #takeWhile(Iterable, groovy.lang.Closure)}
9941      * except that it attempts to preserve the type of the original SortedSet.
9942      * <pre class="groovyTestCase">
9943      * def nums = [ 1, 2, 3 ] as SortedSet
9944      * assert nums.takeWhile{ it < 1 } == [] as SortedSet
9945      * assert nums.takeWhile{ it < 2 } == [ 1 ] as SortedSet
9946      * assert nums.takeWhile{ it < 4 } == [ 1, 2, 3 ] as SortedSet
9947      * </pre>
9948      *
9949      * @param self      the original SortedSet
9950      * @param condition the closure that must evaluate to true to
9951      *                  continue taking elements
9952      * @return a prefix of the given SortedSet where each element passed to
9953      *         the given closure evaluates to true
9954      * @since 2.4.0
9955      */
9956     public static <T> SortedSet<T> takeWhile(SortedSet<T> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure condition) {
9957         return (SortedSet<T>) takeWhile((Iterable<T>) self, condition);
9958     }
9959 
9960     /**
9961      * Returns the longest prefix of this Map where each entry (or key/value pair) when
9962      * passed to the given closure evaluates to true.
9963      * <pre class="groovyTestCase">
9964      * def shopping = [milk:1, bread:2, chocolate:3]
9965      * assert shopping.takeWhile{ it.key.size() < 6 } == [milk:1, bread:2]
9966      * assert shopping.takeWhile{ it.value % 2 } == [milk:1]
9967      * assert shopping.takeWhile{ k, v -> k.size() + v <= 7 } == [milk:1, bread:2]
9968      * </pre>
9969      * If the map instance does not have ordered keys, then this function could appear to take random
9970      * entries. Groovy by default uses LinkedHashMap, so this shouldn't be an issue in the main.
9971      *
9972      * @param self      a Map
9973      * @param condition a 1 (or 2) arg Closure that must evaluate to true for the
9974      *                  entry (or key and value) to continue taking elements
9975      * @return a prefix of the given Map where each entry (or key/value pair) passed to
9976      *         the given closure evaluates to true
9977      * @since 1.8.7
9978      */
9979     public static <K, V> Map<K, V> takeWhile(Map<K, V> self, @ClosureParams(MapEntryOrKeyValue.class) Closure<?> condition) {
9980         if (self.isEmpty()) {
9981             return createSimilarMap(self);
9982         }
9983         Map<K, V> ret = createSimilarMap(self);
9984         BooleanClosureWrapper bcw = new BooleanClosureWrapper(condition);
9985         for (Map.Entry<K, V> entry : self.entrySet()) {
9986             if (!bcw.callForMap(entry)) break;
9987             ret.put(entry.getKey(), entry.getValue());
9988         }
9989         return ret;
9990     }
9991 
9992     /**
9993      * Returns the longest prefix of this array where each element
9994      * passed to the given closure evaluates to true.
9995      * <pre class="groovyTestCase">
9996      * def nums = [ 1, 3, 2 ] as Integer[]
9997      * assert nums.takeWhile{ it < 1 } == [] as Integer[]
9998      * assert nums.takeWhile{ it < 3 } == [ 1 ] as Integer[]
9999      * assert nums.takeWhile{ it < 4 } == [ 1, 3, 2 ] as Integer[]
10000      * </pre>
10001      *
10002      * @param self      the original array
10003      * @param condition the closure that must evaluate to true to
10004      *                  continue taking elements
10005      * @return a prefix of the given array where each element passed to
10006      *         the given closure evaluates to true
10007      * @since 1.8.7
10008      */
10009     public static <T> T[] takeWhile(T[] self, @ClosureParams(FirstParam.Component.class) Closure condition) {
10010         int num = 0;
10011         BooleanClosureWrapper bcw = new BooleanClosureWrapper(condition);
10012         while (num < self.length) {
10013             T value = self[num];
10014             if (bcw.call(value)) {
10015                 num += 1;
10016             } else {
10017                 break;
10018             }
10019         }
10020         return take(self, num);
10021     }
10022 
10023     /**
10024      * Returns the longest prefix of elements in this iterator where
10025      * each element passed to the given condition closure evaluates to true.
10026      * <p>
10027      * <pre class="groovyTestCase">
10028      * def a = 0
10029      * def iter = [ hasNext:{ true }, next:{ a++ } ] as Iterator
10030      *
10031      * assert [].iterator().takeWhile{ it < 3 }.toList() == []
10032      * assert [1, 2, 3, 4, 5].iterator().takeWhile{ it < 3 }.toList() == [ 1, 2 ]
10033      * assert iter.takeWhile{ it < 5 }.toList() == [ 0, 1, 2, 3, 4 ]
10034      * </pre>
10035      *
10036      * @param self      the Iterator
10037      * @param condition the closure that must evaluate to true to
10038      *                  continue taking elements
10039      * @return a prefix of elements in the given iterator where each
10040      *         element passed to the given closure evaluates to true
10041      * @since 1.8.7
10042      */
10043     public static <T> Iterator<T> takeWhile(Iterator<T> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure condition) {
10044         return new TakeWhileIterator<T>(self, condition);
10045     }
10046 
10047     private static final class TakeWhileIterator<E> implements Iterator<E> {
10048         private final Iterator<E> delegate;
10049         private final BooleanClosureWrapper condition;
10050         private boolean exhausted;
10051         private E next;
10052 
10053         private TakeWhileIterator(Iterator<E> delegate, Closure condition) {
10054             this.delegate = delegate;
10055             this.condition = new BooleanClosureWrapper(condition);
10056             advance();
10057         }
10058 
10059         public boolean hasNext() {
10060             return !exhausted;
10061         }
10062 
10063         public E next() {
10064             if (exhausted) throw new NoSuchElementException();
10065             E result = next;
10066             advance();
10067             return result;
10068         }
10069 
10070         public void remove() {
10071             if (exhausted) throw new NoSuchElementException();
10072             delegate.remove();
10073         }
10074 
10075         private void advance() {
10076             exhausted = !delegate.hasNext();
10077             if (!exhausted) {
10078                 next = delegate.next();
10079                 if (!condition.call(next)) {
10080                     exhausted = true;
10081                     next = null;
10082                 }
10083             }
10084         }
10085     }
10086 
10087     /**
10088      * Returns a suffix of this SortedSet where elements are dropped from the front
10089      * while the given Closure evaluates to true.
10090      * Similar to {@link #dropWhile(Iterable, groovy.lang.Closure)}
10091      * except that it attempts to preserve the type of the original SortedSet.
10092      * <pre class="groovyTestCase">
10093      * def nums = [ 1, 2, 3 ] as SortedSet
10094      * assert nums.dropWhile{ it < 4 } == [] as SortedSet
10095      * assert nums.dropWhile{ it < 2 } == [ 2, 3 ] as SortedSet
10096      * assert nums.dropWhile{ it != 3 } == [ 3 ] as SortedSet
10097      * assert nums.dropWhile{ it == 0 } == [ 1, 2, 3 ] as SortedSet
10098      * </pre>
10099      *
10100      * @param self      the original SortedSet
10101      * @param condition the closure that must evaluate to true to continue dropping elements
10102      * @return the shortest suffix of the given SortedSet such that the given closure condition
10103      *         evaluates to true for each element dropped from the front of the SortedSet
10104      * @since 2.4.0
10105      */
10106     public static <T> SortedSet<T> dropWhile(SortedSet<T> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure<?> condition) {
10107         return (SortedSet<T>) dropWhile((Iterable<T>) self, condition);
10108     }
10109 
10110     /**
10111      * Returns a suffix of this List where elements are dropped from the front
10112      * while the given Closure evaluates to true.
10113      * Similar to {@link #dropWhile(Iterable, groovy.lang.Closure)}
10114      * except that it attempts to preserve the type of the original list.
10115      * <pre class="groovyTestCase">
10116      * def nums = [ 1, 3, 2 ]
10117      * assert nums.dropWhile{ it < 4 } == []
10118      * assert nums.dropWhile{ it < 3 } == [ 3, 2 ]
10119      * assert nums.dropWhile{ it != 2 } == [ 2 ]
10120      * assert nums.dropWhile{ it == 0 } == [ 1, 3, 2 ]
10121      * </pre>
10122      *
10123      * @param self      the original list
10124      * @param condition the closure that must evaluate to true to continue dropping elements
10125      * @return the shortest suffix of the given List such that the given closure condition
10126      *         evaluates to true for each element dropped from the front of the List
10127      * @since 1.8.7
10128      */
10129     public static <T> List<T> dropWhile(List<T> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure<?> condition) {
10130         int num = 0;
10131         BooleanClosureWrapper bcw = new BooleanClosureWrapper(condition);
10132         for (T value : self) {
10133             if (bcw.call(value)) {
10134                 num += 1;
10135             } else {
10136                 break;
10137             }
10138         }
10139         return drop(self, num);
10140     }
10141 
10142     /**
10143      * Returns a suffix of this Iterable where elements are dropped from the front
10144      * while the given closure evaluates to true.
10145      * <pre class="groovyTestCase">
10146      * class HorseIterable implements Iterable<String> {
10147      *     Iterator<String> iterator() { "horse".iterator() }
10148      * }
10149      * def horse = new HorseIterable()
10150      * assert horse.dropWhile{ it < 'r' } == ['r', 's', 'e']
10151      * assert horse.dropWhile{ it <= 'r' } == ['s', 'e']
10152      * </pre>
10153      *
10154      * @param self      an Iterable
10155      * @param condition the closure that must evaluate to true to continue dropping elements
10156      * @return a Collection containing the shortest suffix of the given Iterable such that the given closure condition
10157      *         evaluates to true for each element dropped from the front of the Iterable
10158      * @since 1.8.7
10159      */
10160     public static <T> Collection<T> dropWhile(Iterable<T> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure<?> condition) {
10161         Collection<T> selfCol = self instanceof Collection ? (Collection<T>) self : toList(self);
10162         Collection<T> result = createSimilarCollection(selfCol);
10163         addAll(result, dropWhile(self.iterator(), condition));
10164         return result;
10165     }
10166 
10167     /**
10168      * Create a suffix of the given Map by dropping as many entries as possible from the
10169      * front of the original Map such that calling the given closure condition evaluates to
10170      * true when passed each of the dropped entries (or key/value pairs).
10171      * <pre class="groovyTestCase">
10172      * def shopping = [milk:1, bread:2, chocolate:3]
10173      * assert shopping.dropWhile{ it.key.size() < 6 } == [chocolate:3]
10174      * assert shopping.dropWhile{ it.value % 2 } == [bread:2, chocolate:3]
10175      * assert shopping.dropWhile{ k, v -> k.size() + v <= 7 } == [chocolate:3]
10176      * </pre>
10177      * If the map instance does not have ordered keys, then this function could appear to drop random
10178      * entries. Groovy by default uses LinkedHashMap, so this shouldn't be an issue in the main.
10179      *
10180      * @param self      a Map
10181      * @param condition a 1 (or 2) arg Closure that must evaluate to true for the
10182      *                  entry (or key and value) to continue dropping elements
10183      * @return the shortest suffix of the given Map such that the given closure condition
10184      *         evaluates to true for each element dropped from the front of the Map
10185      * @since 1.8.7
10186      */
10187     public static <K, V> Map<K, V> dropWhile(Map<K, V> self, @ClosureParams(MapEntryOrKeyValue.class) Closure<?> condition) {
10188         if (self.isEmpty()) {
10189             return createSimilarMap(self);
10190         }
10191         Map<K, V> ret = createSimilarMap(self);
10192         boolean dropping = true;
10193         BooleanClosureWrapper bcw = new BooleanClosureWrapper(condition);
10194         for (Map.Entry<K, V> entry : self.entrySet()) {
10195             if (dropping && !bcw.callForMap(entry)) dropping = false;
10196             if (!dropping) ret.put(entry.getKey(), entry.getValue());
10197         }
10198         return ret;
10199     }
10200 
10201     /**
10202      * Create a suffix of the given array by dropping as many elements as possible from the
10203      * front of the original array such that calling the given closure condition evaluates to
10204      * true when passed each of the dropped elements.
10205      * <pre class="groovyTestCase">
10206      * def nums = [ 1, 3, 2 ] as Integer[]
10207      * assert nums.dropWhile{ it <= 3 } == [ ] as Integer[]
10208      * assert nums.dropWhile{ it < 3 } == [ 3, 2 ] as Integer[]
10209      * assert nums.dropWhile{ it != 2 } == [ 2 ] as Integer[]
10210      * assert nums.dropWhile{ it == 0 } == [ 1, 3, 2 ] as Integer[]
10211      * </pre>
10212      *
10213      * @param self      the original array
10214      * @param condition the closure that must evaluate to true to
10215      *                  continue dropping elements
10216      * @return the shortest suffix of the given array such that the given closure condition
10217      *         evaluates to true for each element dropped from the front of the array
10218      * @since 1.8.7
10219      */
10220     public static <T> T[] dropWhile(T[] self, @ClosureParams(FirstParam.Component.class) Closure<?> condition) {
10221         int num = 0;
10222         BooleanClosureWrapper bcw = new BooleanClosureWrapper(condition);
10223         while (num < self.length) {
10224             if (bcw.call(self[num])) {
10225                 num += 1;
10226             } else {
10227                 break;
10228             }
10229         }
10230         return drop(self, num);
10231     }
10232 
10233     /**
10234      * Creates an Iterator that returns a suffix of the elements from an original Iterator. As many elements
10235      * as possible are dropped from the front of the original Iterator such that calling the given closure
10236      * condition evaluates to true when passed each of the dropped elements.
10237      * <pre class="groovyTestCase">
10238      * def a = 0
10239      * def iter = [ hasNext:{ a < 10 }, next:{ a++ } ] as Iterator
10240      * assert [].iterator().dropWhile{ it < 3 }.toList() == []
10241      * assert [1, 2, 3, 4, 5].iterator().dropWhile{ it < 3 }.toList() == [ 3, 4, 5 ]
10242      * assert iter.dropWhile{ it < 5 }.toList() == [ 5, 6, 7, 8, 9 ]
10243      * </pre>
10244      *
10245      * @param self      the Iterator
10246      * @param condition the closure that must evaluate to true to continue dropping elements
10247      * @return the shortest suffix of elements from the given Iterator such that the given closure condition
10248      *         evaluates to true for each element dropped from the front of the Iterator
10249      * @since 1.8.7
10250      */
10251     public static <T> Iterator<T> dropWhile(Iterator<T> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure<?> condition) {
10252         return new DropWhileIterator<T>(self, condition);
10253     }
10254 
10255     private static final class DropWhileIterator<E> implements Iterator<E> {
10256         private final Iterator<E> delegate;
10257         private final Closure condition;
10258         private boolean buffering = false;
10259         private E buffer = null;
10260 
10261         private DropWhileIterator(Iterator<E> delegate, Closure condition) {
10262             this.delegate = delegate;
10263             this.condition = condition;
10264             prepare();
10265         }
10266 
10267         public boolean hasNext() {
10268             return buffering || delegate.hasNext();
10269         }
10270 
10271         public E next() {
10272             if (buffering) {
10273                 E result = buffer;
10274                 buffering = false;
10275                 buffer = null;
10276                 return result;
10277             } else {
10278                 return delegate.next();
10279             }
10280         }
10281 
10282         public void remove() {
10283             if (buffering) {
10284                 buffering = false;
10285                 buffer = null;
10286             } else {
10287                 delegate.remove();
10288             }
10289         }
10290 
10291         private void prepare() {
10292             BooleanClosureWrapper bcw = new BooleanClosureWrapper(condition);
10293             while (delegate.hasNext()) {
10294                 E next = delegate.next();
10295                 if (!bcw.call(next)) {
10296                     buffer = next;
10297                     buffering = true;
10298                     break;
10299                 }
10300             }
10301         }
10302     }
10303 
10304     /**
10305      * Converts this Iterable to a Collection. Returns the original Iterable
10306      * if it is already a Collection.
10307      * <p>
10308      * Example usage:
10309      * <pre class="groovyTestCase">
10310      * assert new HashSet().asCollection() instanceof Collection
10311      * </pre>
10312      *
10313      * @param self an Iterable to be converted into a Collection
10314      * @return a newly created List if this Iterable is not already a Collection
10315      * @since 2.4.0
10316      */
10317     public static <T> Collection<T> asCollection(Iterable<T> self) {
10318         if (self instanceof Collection) {
10319             return (Collection<T>) self;
10320         } else {
10321             return toList(self);
10322         }
10323     }
10324 
10325     /**
10326      * @deprecated Use the Iterable version of asList instead
10327      * @see #asList(Iterable)
10328      * @since 1.0
10329      */
10330     @Deprecated
10331     public static <T> List<T> asList(Collection<T> self) {
10332         return asList((Iterable<T>)self);
10333     }
10334 
10335     /**
10336      * Converts this Iterable to a List. Returns the original Iterable
10337      * if it is already a List.
10338      * <p>
10339      * Example usage:
10340      * <pre class="groovyTestCase">
10341      * assert new HashSet().asList() instanceof List
10342      * </pre>
10343      *
10344      * @param self an Iterable to be converted into a List
10345      * @return a newly created List if this Iterable is not already a List
10346      * @since 2.2.0
10347      */
10348     public static <T> List<T> asList(Iterable<T> self) {
10349         if (self instanceof List) {
10350             return (List<T>) self;
10351         } else {
10352             return toList(self);
10353         }
10354     }
10355 
10356     /**
10357      * Coerce an object instance to a boolean value.
10358      * An object is coerced to true if it's not null, to false if it is null.
10359      *
10360      * @param object the object to coerce
10361      * @return the boolean value
10362      * @since 1.7.0
10363      */
10364     public static boolean asBoolean(Object object) {
10365         return object != null;
10366     }
10367 
10368     /**
10369      * Coerce an Boolean instance to a boolean value.
10370      *
10371      * @param bool the Boolean
10372      * @return the boolean value
10373      * @since 1.7.0
10374      */
10375     public static boolean asBoolean(Boolean bool) {
10376         return bool;
10377     }
10378 
10379     /**
10380      * Coerce a collection instance to a boolean value.
10381      * A collection is coerced to false if it's empty, and to true otherwise.
10382      * <pre class="groovyTestCase">assert [1,2].asBoolean() == true</pre>
10383      * <pre class="groovyTestCase">assert [].asBoolean() == false</pre>
10384      *
10385      * @param collection the collection
10386      * @return the boolean value
10387      * @since 1.7.0
10388      */
10389     public static boolean asBoolean(Collection collection) {
10390         return !collection.isEmpty();
10391     }
10392 
10393     /**
10394      * Coerce a map instance to a boolean value.
10395      * A map is coerced to false if it's empty, and to true otherwise.
10396      * <pre class="groovyTestCase">assert [:] as Boolean == false
10397      * assert [a:2] as Boolean == true</pre>
10398      *
10399      * @param map the map
10400      * @return the boolean value
10401      * @since 1.7.0
10402      */
10403     public static boolean asBoolean(Map map) {
10404         return !map.isEmpty();
10405     }
10406 
10407     /**
10408      * Coerce an iterator instance to a boolean value.
10409      * An iterator is coerced to false if there are no more elements to iterate over,
10410      * and to true otherwise.
10411      *
10412      * @param iterator the iterator
10413      * @return the boolean value
10414      * @since 1.7.0
10415      */
10416     public static boolean asBoolean(Iterator iterator) {
10417         return iterator.hasNext();
10418     }
10419 
10420     /**
10421      * Coerce an enumeration instance to a boolean value.
10422      * An enumeration is coerced to false if there are no more elements to enumerate,
10423      * and to true otherwise.
10424      *
10425      * @param enumeration the enumeration
10426      * @return the boolean value
10427      * @since 1.7.0
10428      */
10429     public static boolean asBoolean(Enumeration enumeration) {
10430         return enumeration.hasMoreElements();
10431     }
10432 
10433     /**
10434      * Coerce an Object array to a boolean value.
10435      * An Object array is false if the array is of length 0.
10436      * and to true otherwise
10437      *
10438      * @param array the array
10439      * @return the boolean value
10440      * @since 1.7.0
10441      */
10442     public static boolean asBoolean(Object[] array) {
10443         return array.length > 0;
10444     }
10445 
10446     /**
10447      * Coerces a byte array to a boolean value.
10448      * A byte array is false if the array is of length 0,
10449      * and true otherwise.
10450      *
10451      * @param array an array
10452      * @return the array's boolean value
10453      * @since 1.7.4
10454      */
10455     public static boolean asBoolean(byte[] array) {
10456         return array.length > 0;
10457     }
10458 
10459     /**
10460      * Coerces a short array to a boolean value.
10461      * A short array is false if the array is of length 0,
10462      * and true otherwise.
10463      *
10464      * @param array an array
10465      * @return the array's boolean value
10466      * @since 1.7.4
10467      */
10468     public static boolean asBoolean(short[] array) {
10469         return array.length > 0;
10470     }
10471 
10472     /**
10473      * Coerces an int array to a boolean value.
10474      * An int array is false if the array is of length 0,
10475      * and true otherwise.
10476      *
10477      * @param array an array
10478      * @return the array's boolean value
10479      * @since 1.7.4
10480      */
10481     public static boolean asBoolean(int[] array) {
10482         return array.length > 0;
10483     }
10484 
10485     /**
10486      * Coerces a long array to a boolean value.
10487      * A long array is false if the array is of length 0,
10488      * and true otherwise.
10489      *
10490      * @param array an array
10491      * @return the array's boolean value
10492      * @since 1.7.4
10493      */
10494     public static boolean asBoolean(long[] array) {
10495         return array.length > 0;
10496     }
10497 
10498     /**
10499      * Coerces a float array to a boolean value.
10500      * A float array is false if the array is of length 0,
10501      * and true otherwise.
10502      *
10503      * @param array an array
10504      * @return the array's boolean value
10505      * @since 1.7.4
10506      */
10507     public static boolean asBoolean(float[] array) {
10508         return array.length > 0;
10509     }
10510 
10511     /**
10512      * Coerces a double array to a boolean value.
10513      * A double array is false if the array is of length 0,
10514      * and true otherwise.
10515      *
10516      * @param array an array
10517      * @return the array's boolean value
10518      * @since 1.7.4
10519      */
10520     public static boolean asBoolean(double[] array) {
10521         return array.length > 0;
10522     }
10523 
10524     /**
10525      * Coerces a boolean array to a boolean value.
10526      * A boolean array is false if the array is of length 0,
10527      * and true otherwise.
10528      *
10529      * @param array an array
10530      * @return the array's boolean value
10531      * @since 1.7.4
10532      */
10533     public static boolean asBoolean(boolean[] array) {
10534         return array.length > 0;
10535     }
10536 
10537     /**
10538      * Coerces a char array to a boolean value.
10539      * A char array is false if the array is of length 0,
10540      * and true otherwise.
10541      *
10542      * @param array an array
10543      * @return the array's boolean value
10544      * @since 1.7.4
10545      */
10546     public static boolean asBoolean(char[] array) {
10547         return array.length > 0;
10548     }
10549 
10550     /**
10551      * Coerce a character to a boolean value.
10552      * A character is coerced to false if it's character value is equal to 0,
10553      * and to true otherwise.
10554      *
10555      * @param character the character
10556      * @return the boolean value
10557      * @since 1.7.0
10558      */
10559 
10560     public static boolean asBoolean(Character character) {
10561         return character != 0;
10562     }
10563 
10564     /**
10565      * Coerce a number to a boolean value.
10566      * A number is coerced to false if its double value is equal to 0, and to true otherwise,
10567      * and to true otherwise.
10568      *
10569      * @param number the number
10570      * @return the boolean value
10571      * @since 1.7.0
10572      */
10573     public static boolean asBoolean(Number number) {
10574         return number.doubleValue() != 0;
10575     }
10576 
10577     /**
10578      * Converts the given collection to another type. A default concrete
10579      * type is used for List, Set, or SortedSet. If the given type has
10580      * a constructor taking a collection, that is used. Otherwise, the
10581      * call is deferred to {link #asType(Object,Class)}.  If this
10582      * collection is already of the given type, the same instance is
10583      * returned.
10584      *
10585      * @param col   a collection
10586      * @param clazz the desired class
10587      * @return the object resulting from this type conversion
10588      * @see #asType(java.lang.Object, java.lang.Class)
10589      * @since 1.0
10590      */
10591     @SuppressWarnings("unchecked")
10592     public static <T> T asType(Collection col, Class<T> clazz) {
10593         if (col.getClass() == clazz) {
10594             return (T) col;
10595         }
10596         if (clazz == List.class) {
10597             return (T) asList((Iterable) col);
10598         }
10599         if (clazz == Set.class) {
10600             if (col instanceof Set) return (T) col;
10601             return (T) new LinkedHashSet(col);
10602         }
10603         if (clazz == SortedSet.class) {
10604             if (col instanceof SortedSet) return (T) col;
10605             return (T) new TreeSet(col);
10606         }
10607         if (clazz == Queue.class) {
10608             if (col instanceof Queue) return (T) col;
10609             return (T) new LinkedList(col);
10610         }
10611         if (clazz == Stack.class) {
10612             if (col instanceof Stack) return (T) col;
10613             final Stack stack = new Stack();
10614             stack.addAll(col);
10615             return (T) stack;
10616         }
10617 
10618         if (clazz!=String[].class && ReflectionCache.isArray(clazz)) {
10619             try {
10620                 return (T) asArrayType(col, clazz);
10621             } catch (GroovyCastException e) {
10622                 /* ignore */
10623             }
10624         }
10625 
10626         Object[] args = {col};
10627         try {
10628             return (T) InvokerHelper.invokeConstructorOf(clazz, args);
10629         } catch (Exception e) {
10630             // ignore, the constructor that takes a Collection as an argument may not exist
10631         }
10632         if (Collection.class.isAssignableFrom(clazz)) {
10633             try {
10634                 Collection result = (Collection) InvokerHelper.invokeConstructorOf(clazz, null);
10635                 result.addAll(col);
10636                 return (T)result;
10637             } catch (Exception e) {
10638                 // ignore, the no arg constructor might not exist.
10639             }
10640         }
10641 
10642         return asType((Object) col, clazz);
10643     }
10644 
10645     /**
10646      * Converts the given array to either a List, Set, or
10647      * SortedSet.  If the given class is something else, the
10648      * call is deferred to {link #asType(Object,Class)}.
10649      *
10650      * @param ary   an array
10651      * @param clazz the desired class
10652      * @return the object resulting from this type conversion
10653      * @see #asType(java.lang.Object, java.lang.Class)
10654      * @since 1.5.1
10655      */
10656     @SuppressWarnings("unchecked")
10657     public static <T> T asType(Object[] ary, Class<T> clazz) {
10658         if (clazz == List.class) {
10659             return (T) new ArrayList(Arrays.asList(ary));
10660         }
10661         if (clazz == Set.class) {
10662             return (T) new HashSet(Arrays.asList(ary));
10663         }
10664         if (clazz == SortedSet.class) {
10665             return (T) new TreeSet(Arrays.asList(ary));
10666         }
10667 
10668         return asType((Object) ary, clazz);
10669     }
10670 
10671     /**
10672      * Coerces the closure to an implementation of the given class.  The class
10673      * is assumed to be an interface or class with a single method definition.
10674      * The closure is used as the implementation of that single method.
10675      *
10676      * @param cl    the implementation of the single method
10677      * @param clazz the target type
10678      * @return a Proxy of the given type which wraps this closure.
10679      * @since 1.0
10680      */
10681     @SuppressWarnings("unchecked")
10682     public static <T> T asType(Closure cl, Class<T> clazz) {
10683         if (clazz.isInterface() && !(clazz.isInstance(cl))) {
10684             if (Traits.isTrait(clazz)) {
10685                 Method samMethod = CachedSAMClass.getSAMMethod(clazz);
10686                 if (samMethod!=null) {
10687                     Map impl = Collections.singletonMap(samMethod.getName(),cl);
10688                     return (T) ProxyGenerator.INSTANCE.instantiateAggregate(impl, Collections.<Class>singletonList(clazz));
10689                 }
10690             }
10691             return (T) Proxy.newProxyInstance(
10692                     clazz.getClassLoader(),
10693                     new Class[]{clazz},
10694                     new ConvertedClosure(cl));
10695         }
10696         try {
10697             return asType((Object) cl, clazz);
10698         } catch (GroovyCastException ce) {
10699             try {
10700                 return (T) ProxyGenerator.INSTANCE.instantiateAggregateFromBaseClass(cl, clazz);
10701             } catch (GroovyRuntimeException cause) {
10702                 throw new GroovyCastException("Error casting closure to " + clazz.getName() +
10703                         ", Reason: " + cause.getMessage());
10704             }
10705         }
10706     }
10707 
10708     /**
10709      * Coerces this map to the given type, using the map's keys as the public
10710      * method names, and values as the implementation.  Typically the value
10711      * would be a closure which behaves like the method implementation.
10712      *
10713      * @param map   this map
10714      * @param clazz the target type
10715      * @return a Proxy of the given type, which defers calls to this map's elements.
10716      * @since 1.0
10717      */
10718     @SuppressWarnings("unchecked")
10719     public static <T> T asType(Map map, Class<T> clazz) {
10720         if (!(clazz.isInstance(map)) && clazz.isInterface() && !Traits.isTrait(clazz)) {
10721             return (T) Proxy.newProxyInstance(
10722                     clazz.getClassLoader(),
10723                     new Class[]{clazz},
10724                     new ConvertedMap(map));
10725         }
10726         try {
10727             return asType((Object) map, clazz);
10728         } catch (GroovyCastException ce) {
10729             try {
10730                 return (T) ProxyGenerator.INSTANCE.instantiateAggregateFromBaseClass(map, clazz);
10731             } catch (GroovyRuntimeException cause) {
10732                 throw new GroovyCastException("Error casting map to " + clazz.getName() +
10733                         ", Reason: " + cause.getMessage());
10734             }
10735         }
10736     }
10737 
10738     /**
10739      * Creates a new List with the identical contents to this list
10740      * but in reverse order.
10741      * <pre class="groovyTestCase">
10742      * def list = ["a", 4, false]
10743      * assert list.reverse() == [false, 4, "a"]
10744      * assert list == ["a", 4, false]
10745      * </pre>
10746      *
10747      * @param self a List
10748      * @return a reversed List
10749      * @see #reverse(List, boolean)
10750      * @since 1.0
10751      */
10752     public static <T> List<T> reverse(List<T> self) {
10753         return reverse(self, false);
10754     }
10755 
10756     /**
10757      * Reverses the elements in a list. If mutate is true, the original list is modified in place and returned.
10758      * Otherwise, a new list containing the reversed items is produced.
10759      * <pre class="groovyTestCase">
10760      * def list = ["a", 4, false]
10761      * assert list.reverse(false) == [false, 4, "a"]
10762      * assert list == ["a", 4, false]
10763      * assert list.reverse(true) == [false, 4, "a"]
10764      * assert list == [false, 4, "a"]
10765      * </pre>
10766      *
10767      * @param self a List
10768      * @param mutate true if the list itself should be reversed in place and returned, false if a new list should be created
10769      * @return a reversed List
10770      * @since 1.8.1
10771      */
10772     public static <T> List<T> reverse(List<T> self, boolean mutate) {
10773         if (mutate) {
10774             Collections.reverse(self);
10775             return self;
10776         }
10777         int size = self.size();
10778         List<T> answer = new ArrayList<T>(size);
10779         ListIterator<T> iter = self.listIterator(size);
10780         while (iter.hasPrevious()) {
10781             answer.add(iter.previous());
10782         }
10783         return answer;
10784     }
10785 
10786     /**
10787      * Creates a new array containing items which are the same as this array but in reverse order.
10788      *
10789      * @param self    an array
10790      * @return an array containing the reversed items
10791      * @see #reverse(Object[], boolean)
10792      * @since 1.5.5
10793      */
10794     @SuppressWarnings("unchecked")
10795     public static <T> T[] reverse(T[] self) {
10796         return reverse(self, false);
10797     }
10798 
10799     /**
10800      * Reverse the items in an array. If mutate is true, the original array is modified in place and returned.
10801      * Otherwise, a new array containing the reversed items is produced.
10802      *
10803      * @param self   an array
10804      * @param mutate true if the array itself should be reversed in place and returned, false if a new array should be created
10805      * @return an array containing the reversed items
10806      * @since 1.8.1
10807      */
10808     @SuppressWarnings("unchecked")
10809     public static <T> T[] reverse(T[] self, boolean mutate) {
10810         if (!mutate) {
10811             return (T[]) toList(new ReverseListIterator<T>(Arrays.asList(self))).toArray();
10812         }
10813         List<T> items = Arrays.asList(self);
10814         Collections.reverse(items);
10815         System.arraycopy(items.toArray(), 0, self, 0, items.size());
10816         return self;
10817     }
10818 
10819     /**
10820      * Reverses the iterator. The original iterator will become
10821      * exhausted of elements after determining the reversed values.
10822      * A new iterator for iterating through the reversed values is returned.
10823      *
10824      * @param self an Iterator
10825      * @return a reversed Iterator
10826      * @since 1.5.5
10827      */
10828     public static <T> Iterator<T> reverse(Iterator<T> self) {
10829         return new ReverseListIterator<T>(toList(self));
10830     }
10831 
10832     /**
10833      * Create an array as a union of two arrays.
10834      * <pre class="groovyTestCase">
10835      * Integer[] a = [1, 2, 3]
10836      * Integer[] b = [4, 5, 6]
10837      * assert a + b == [1, 2, 3, 4, 5, 6] as Integer[]
10838      * </pre>
10839      *
10840      * @param left  the left Array
10841      * @param right the right Array
10842      * @return A new array containing right appended to left.
10843      * @since 1.8.7
10844      */
10845     @SuppressWarnings("unchecked")
10846     public static <T> T[] plus(T[] left, T[] right) {
10847         return (T[]) plus(toList(left), toList(right)).toArray();
10848     }
10849 
10850     /**
10851      * Create an array containing elements from an original array plus an additional appended element.
10852      * <pre class="groovyTestCase">
10853      * Integer[] a = [1, 2, 3]
10854      * Integer[] result = a + 4
10855      * assert result == [1, 2, 3, 4] as Integer[]
10856      * </pre>
10857      *
10858      * @param left  the array
10859      * @param right the value to append
10860      * @return A new array containing left with right appended to it.
10861      * @since 1.8.7
10862      */
10863     @SuppressWarnings("unchecked")
10864     public static <T> T[] plus(T[] left, T right) {
10865         return (T[]) plus(toList(left), right).toArray();
10866     }
10867 
10868     /**
10869      * Create an array containing elements from an original array plus those from a Collection.
10870      * <pre class="groovyTestCase">
10871      * Integer[] a = [1, 2, 3]
10872      * def additions = [7, 8]
10873      * assert a + additions == [1, 2, 3, 7, 8] as Integer[]
10874      * </pre>
10875      *
10876      * @param left  the array
10877      * @param right a Collection to be appended
10878      * @return A new array containing left with right appended to it.
10879      * @since 1.8.7
10880      */
10881     @SuppressWarnings("unchecked")
10882     public static <T> T[] plus(T[] left, Collection<T> right) {
10883         return (T[]) plus(toList(left), right).toArray();
10884     }
10885 
10886     /**
10887      * Create an array containing elements from an original array plus those from an Iterable.
10888      * <pre class="groovyTestCase">
10889      * class AbcIterable implements Iterable<String> {
10890      *     Iterator<String> iterator() { "abc".iterator() }
10891      * }
10892      * String[] letters = ['x', 'y', 'z']
10893      * def result = letters + new AbcIterable()
10894      * assert result == ['x', 'y', 'z', 'a', 'b', 'c'] as String[]
10895      * assert result.class.array
10896      * </pre>
10897      *
10898      * @param left  the array
10899      * @param right an Iterable to be appended
10900      * @return A new array containing elements from left with those from right appended.
10901      * @since 1.8.7
10902      */
10903     @SuppressWarnings("unchecked")
10904     public static <T> T[] plus(T[] left, Iterable<T> right) {
10905         return (T[]) plus(toList(left), toList(right)).toArray();
10906     }
10907 
10908     /**
10909      * Create a Collection as a union of two collections. If the left collection
10910      * is a Set, then the returned collection will be a Set otherwise a List.
10911      * This operation will always create a new object for the result,
10912      * while the operands remain unchanged.
10913      * <pre class="groovyTestCase">assert [1,2,3,4] == [1,2] + [3,4]</pre>
10914      *
10915      * @param left  the left Collection
10916      * @param right the right Collection
10917      * @return the merged Collection
10918      * @since 1.5.0
10919      */
10920     public static <T> Collection<T> plus(Collection<T> left, Collection<T> right) {
10921         final Collection<T> answer = cloneSimilarCollection(left, left.size() + right.size());
10922         answer.addAll(right);
10923         return answer;
10924     }
10925 
10926     /**
10927      * Create a Collection as a union of two iterables. If the left iterable
10928      * is a Set, then the returned collection will be a Set otherwise a List.
10929      * This operation will always create a new object for the result,
10930      * while the operands remain unchanged.
10931      * <pre class="groovyTestCase">assert [1,2,3,4] == [1,2] + [3,4]</pre>
10932      *
10933      * @param left  the left Iterable
10934      * @param right the right Iterable
10935      * @return the merged Collection
10936      * @since 2.4.0
10937      */
10938     public static <T> Collection<T> plus(Iterable<T> left, Iterable<T> right) {
10939         return plus(asCollection(left), asCollection(right));
10940     }
10941 
10942     /**
10943      * Create a Collection as a union of a Collection and an Iterable. If the left collection
10944      * is a Set, then the returned collection will be a Set otherwise a List.
10945      * This operation will always create a new object for the result,
10946      * while the operands remain unchanged.
10947      *
10948      * @param left  the left Collection
10949      * @param right the right Iterable
10950      * @return the merged Collection
10951      * @since 1.8.7
10952      * @see #plus(Collection, Collection)
10953      */
10954     public static <T> Collection<T> plus(Collection<T> left, Iterable<T> right) {
10955         return plus(left, asCollection(right));
10956     }
10957 
10958     /**
10959      * Create a List as a union of a List and an Iterable.
10960      * This operation will always create a new object for the result,
10961      * while the operands remain unchanged.
10962      *
10963      * @param left  the left List
10964      * @param right the right Iterable
10965      * @return the merged List
10966      * @since 2.4.0
10967      * @see #plus(Collection, Collection)
10968      */
10969     public static <T> List<T> plus(List<T> left, Iterable<T> right) {
10970         return (List<T>) plus((Collection<T>) left, asCollection(right));
10971     }
10972 
10973     /**
10974      * Create a List as a union of a List and an Collection.
10975      * This operation will always create a new object for the result,
10976      * while the operands remain unchanged.
10977      *
10978      * @param left  the left List
10979      * @param right the right Collection
10980      * @return the merged List
10981      * @since 2.4.0
10982      * @see #plus(Collection, Collection)
10983      */
10984     public static <T> List<T> plus(List<T> left, Collection<T> right) {
10985         return (List<T>) plus((Collection<T>) left, right);
10986     }
10987 
10988     /**
10989      * Create a Set as a union of a Set and an Iterable.
10990      * This operation will always create a new object for the result,
10991      * while the operands remain unchanged.
10992      *
10993      * @param left  the left Set
10994      * @param right the right Iterable
10995      * @return the merged Set
10996      * @since 2.4.0
10997      * @see #plus(Collection, Collection)
10998      */
10999     public static <T> Set<T> plus(Set<T> left, Iterable<T> right) {
11000         return (Set<T>) plus((Collection<T>) left, asCollection(right));
11001     }
11002 
11003     /**
11004      * Create a Set as a union of a Set and an Collection.
11005      * This operation will always create a new object for the result,
11006      * while the operands remain unchanged.
11007      *
11008      * @param left  the left Set
11009      * @param right the right Collection
11010      * @return the merged Set
11011      * @since 2.4.0
11012      * @see #plus(Collection, Collection)
11013      */
11014     public static <T> Set<T> plus(Set<T> left, Collection<T> right) {
11015         return (Set<T>) plus((Collection<T>) left, right);
11016     }
11017 
11018     /**
11019      * Create a SortedSet as a union of a SortedSet and an Iterable.
11020      * This operation will always create a new object for the result,
11021      * while the operands remain unchanged.
11022      *
11023      * @param left  the left SortedSet
11024      * @param right the right Iterable
11025      * @return the merged SortedSet
11026      * @since 2.4.0
11027      * @see #plus(Collection, Collection)
11028      */
11029     public static <T> SortedSet<T> plus(SortedSet<T> left, Iterable<T> right) {
11030         return (SortedSet<T>) plus((Collection<T>) left, asCollection(right));
11031     }
11032 
11033     /**
11034      * Create a SortedSet as a union of a SortedSet and an Collection.
11035      * This operation will always create a new object for the result,
11036      * while the operands remain unchanged.
11037      *
11038      * @param left  the left SortedSet
11039      * @param right the right Collection
11040      * @return the merged SortedSet
11041      * @since 2.4.0
11042      * @see #plus(Collection, Collection)
11043      */
11044     public static <T> SortedSet<T> plus(SortedSet<T> left, Collection<T> right) {
11045         return (SortedSet<T>) plus((Collection<T>) left, right);
11046     }
11047 
11048     /**
11049      * Creates a new List by inserting all of the elements in the specified array
11050      * to the elements from the original List at the specified index.
11051      * Shifts the element currently at that index (if any) and any subsequent
11052      * elements to the right (increasing their indices).
11053      * The new elements will appear in the resulting List in the order that
11054      * they occur in the original array.
11055      * The behavior of this operation is undefined if the list or
11056      * array operands are modified while the operation is in progress.
11057      * The original list and array operands remain unchanged.
11058      *
11059      * <pre class="groovyTestCase">
11060      * def items = [1, 2, 3]
11061      * def newItems = items.plus(2, 'a'..'c' as String[])
11062      * assert newItems == [1, 2, 'a', 'b', 'c', 3]
11063      * assert items == [1, 2, 3]
11064      * </pre>
11065      *
11066      * See also <code>addAll</code> for similar functionality with modify semantics, i.e. which performs
11067      * the changes on the original list itself.
11068      *
11069      * @param self  an original list
11070      * @param items array containing elements to be merged with elements from the original list
11071      * @param index index at which to insert the first element from the specified array
11072      * @return the new list
11073      * @see #plus(List, int, List)
11074      * @since 1.8.1
11075      */
11076     public static <T> List<T> plus(List<T> self, int index, T[] items) {
11077         return plus(self, index, Arrays.asList(items));
11078     }
11079 
11080     /**
11081      * Creates a new List by inserting all of the elements in the given additions List
11082      * to the elements from the original List at the specified index.
11083      * Shifts the element currently at that index (if any) and any subsequent
11084      * elements to the right (increasing their indices).  The new elements
11085      * will appear in the resulting List in the order that they occur in the original lists.
11086      * The behavior of this operation is undefined if the original lists
11087      * are modified while the operation is in progress. The original lists remain unchanged.
11088      *
11089      * <pre class="groovyTestCase">
11090      * def items = [1, 2, 3]
11091      * def newItems = items.plus(2, 'a'..'c')
11092      * assert newItems == [1, 2, 'a', 'b', 'c', 3]
11093      * assert items == [1, 2, 3]
11094      * </pre>
11095      *
11096      * See also <code>addAll</code> for similar functionality with modify semantics, i.e. which performs
11097      * the changes on the original list itself.
11098      *
11099      * @param self      an original List
11100      * @param additions a List containing elements to be merged with elements from the original List
11101      * @param index     index at which to insert the first element from the given additions List
11102      * @return the new list
11103      * @since 1.8.1
11104      */
11105     public static <T> List<T> plus(List<T> self, int index, List<T> additions) {
11106         final List<T> answer = new ArrayList<T>(self);
11107         answer.addAll(index, additions);
11108         return answer;
11109     }
11110 
11111     /**
11112      * Creates a new List by inserting all of the elements in the given Iterable
11113      * to the elements from this List at the specified index.
11114      *
11115      * @param self      an original list
11116      * @param additions an Iterable containing elements to be merged with the elements from the original List
11117      * @param index     index at which to insert the first element from the given additions Iterable
11118      * @return the new list
11119      * @since 1.8.7
11120      * @see #plus(List, int, List)
11121      */
11122     public static <T> List<T> plus(List<T> self, int index, Iterable<T> additions) {
11123         return plus(self, index, toList(additions));
11124     }
11125 
11126     /**
11127      * Create a collection as a union of a Collection and an Object. If the collection
11128      * is a Set, then the returned collection will be a Set otherwise a List.
11129      * This operation will always create a new object for the result,
11130      * while the operands remain unchanged.
11131      * <pre class="groovyTestCase">assert [1,2,3] == [1,2] + 3</pre>
11132      *
11133      * @param left  a Collection
11134      * @param right an object to add/append
11135      * @return the resulting Collection
11136      * @since 1.5.0
11137      */
11138     public static <T> Collection<T> plus(Collection<T> left, T right) {
11139         final Collection<T> answer = cloneSimilarCollection(left, left.size() + 1);
11140         answer.add(right);
11141         return answer;
11142     }
11143 
11144     /**
11145      * Create a collection as a union of an Iterable and an Object. If the iterable
11146      * is a Set, then the returned collection will be a Set otherwise a List.
11147      * This operation will always create a new object for the result,
11148      * while the operands remain unchanged.
11149      * <pre class="groovyTestCase">assert [1,2,3] == [1,2] + 3</pre>
11150      *
11151      * @param left  an Iterable
11152      * @param right an object to add/append
11153      * @return the resulting Collection
11154      * @since 2.4.0
11155      */
11156     public static <T> Collection<T> plus(Iterable<T> left, T right) {
11157         return plus(asCollection(left), right);
11158     }
11159 
11160     /**
11161      * Create a List as a union of a List and an Object.
11162      * This operation will always create a new object for the result,
11163      * while the operands remain unchanged.
11164      * <pre class="groovyTestCase">assert [1,2,3] == [1,2] + 3</pre>
11165      *
11166      * @param left  a List
11167      * @param right an object to add/append
11168      * @return the resulting List
11169      * @since 2.4.0
11170      */
11171     public static <T> List<T> plus(List<T> left, T right) {
11172         return (List<T>) plus((Collection<T>) left, right);
11173     }
11174 
11175     /**
11176      * Create a Set as a union of a Set and an Object.
11177      * This operation will always create a new object for the result,
11178      * while the operands remain unchanged.
11179      * <pre class="groovyTestCase">assert [1,2,3] == [1,2] + 3</pre>
11180      *
11181      * @param left  a Set
11182      * @param right an object to add/append
11183      * @return the resulting Set
11184      * @since 2.4.0
11185      */
11186     public static <T> Set<T> plus(Set<T> left, T right) {
11187         return (Set<T>) plus((Collection<T>) left, right);
11188     }
11189 
11190     /**
11191      * Create a SortedSet as a union of a SortedSet and an Object.
11192      * This operation will always create a new object for the result,
11193      * while the operands remain unchanged.
11194      * <pre class="groovyTestCase">assert [1,2,3] == [1,2] + 3</pre>
11195      *
11196      * @param left  a SortedSet
11197      * @param right an object to add/append
11198      * @return the resulting SortedSet
11199      * @since 2.4.0
11200      */
11201     public static <T> SortedSet<T> plus(SortedSet<T> left, T right) {
11202         return (SortedSet<T>) plus((Collection<T>) left, right);
11203     }
11204 
11205     /**
11206      * @deprecated use the Iterable variant instead
11207      * @see #multiply(Iterable, Number)
11208      * @since 1.0
11209      */
11210     @Deprecated
11211     public static <T> Collection<T> multiply(Collection<T> self, Number factor) {
11212         return multiply((Iterable<T>) self, factor);
11213     }
11214 
11215     /**
11216      * Create a Collection composed of the elements of this Iterable, repeated
11217      * a certain number of times.  Note that for non-primitive
11218      * elements, multiple references to the same instance will be added.
11219      * <pre class="groovyTestCase">assert [1,2,3,1,2,3] == [1,2,3] * 2</pre>
11220      *
11221      * Note: if the Iterable happens to not support duplicates, e.g. a Set, then the
11222      * method will effectively return a Collection with a single copy of the Iterable's items.
11223      *
11224      * @param self   an Iterable
11225      * @param factor the number of times to append
11226      * @return the multiplied Collection
11227      * @since 2.4.0
11228      */
11229     public static <T> Collection<T> multiply(Iterable<T> self, Number factor) {
11230         Collection<T> selfCol = asCollection(self);
11231         int size = factor.intValue();
11232         Collection<T> answer = createSimilarCollection(selfCol, selfCol.size() * size);
11233         for (int i = 0; i < size; i++) {
11234             answer.addAll(selfCol);
11235         }
11236         return answer;
11237     }
11238 
11239     /**
11240      * Create a List composed of the elements of this Iterable, repeated
11241      * a certain number of times.  Note that for non-primitive
11242      * elements, multiple references to the same instance will be added.
11243      * <pre class="groovyTestCase">assert [1,2,3,1,2,3] == [1,2,3] * 2</pre>
11244      *
11245      * Note: if the Iterable happens to not support duplicates, e.g. a Set, then the
11246      * method will effectively return a Collection with a single copy of the Iterable's items.
11247      *
11248      * @param self   a List
11249      * @param factor the number of times to append
11250      * @return the multiplied List
11251      * @since 2.4.0
11252      */
11253     public static <T> List<T> multiply(List<T> self, Number factor) {
11254         return (List<T>) multiply((Iterable<T>) self, factor);
11255     }
11256 
11257     /**
11258      * Create a Collection composed of the intersection of both collections.  Any
11259      * elements that exist in both collections are added to the resultant collection.
11260      * <pre class="groovyTestCase">assert [4,5] == [1,2,3,4,5].intersect([4,5,6,7,8])</pre>
11261      *
11262      * @param left  a Collection
11263      * @param right a Collection
11264      * @return a Collection as an intersection of both collections
11265      * @since 1.5.6
11266      */
11267     public static <T> Collection<T> intersect(Collection<T> left, Collection<T> right) {
11268         if (left.isEmpty() || right.isEmpty())
11269             return createSimilarCollection(left, 0);
11270 
11271         if (left.size() < right.size()) {
11272             Collection<T> swaptemp = left;
11273             left = right;
11274             right = swaptemp;
11275         }
11276 
11277         // TODO optimise if same type?
11278         // boolean nlgnSort = sameType(new Collection[]{left, right});
11279 
11280         Collection<T> result = createSimilarCollection(left, left.size());
11281         //creates the collection to look for values.
11282         Collection<T> pickFrom = new TreeSet<T>(new NumberAwareComparator<T>());
11283         pickFrom.addAll(left);
11284 
11285         for (final T t : right) {
11286             if (pickFrom.contains(t))
11287                 result.add(t);
11288         }
11289         return result;
11290     }
11291 
11292     /**
11293      * Create a Collection composed of the intersection of both iterables.  Any
11294      * elements that exist in both iterables are added to the resultant collection.
11295      * <pre class="groovyTestCase">assert [4,5] == [1,2,3,4,5].intersect([4,5,6,7,8])</pre>
11296      *
11297      * @param left  an Iterable
11298      * @param right an Iterable
11299      * @return a Collection as an intersection of both iterables
11300      * @since 2.4.0
11301      */
11302     public static <T> Collection<T> intersect(Iterable<T> left, Iterable<T> right) {
11303         return intersect(asCollection(left), asCollection(right));
11304     }
11305 
11306     /**
11307      * Create a List composed of the intersection of a List and an Iterable.  Any
11308      * elements that exist in both iterables are added to the resultant collection.
11309      * <pre class="groovyTestCase">assert [4,5] == [1,2,3,4,5].intersect([4,5,6,7,8])</pre>
11310      *
11311      * @param left  a List
11312      * @param right an Iterable
11313      * @return a List as an intersection of a List and an Iterable
11314      * @since 2.4.0
11315      */
11316     public static <T> List<T> intersect(List<T> left, Iterable<T> right) {
11317         return (List<T>) intersect((Collection<T>) left, asCollection(right));
11318     }
11319 
11320     /**
11321      * Create a Set composed of the intersection of a Set and an Iterable.  Any
11322      * elements that exist in both iterables are added to the resultant collection.
11323      * <pre class="groovyTestCase">assert [4,5] as Set == ([1,2,3,4,5] as Set).intersect([4,5,6,7,8])</pre>
11324      *
11325      * @param left  a Set
11326      * @param right an Iterable
11327      * @return a Set as an intersection of a Set and an Iterable
11328      * @since 2.4.0
11329      */
11330     public static <T> Set<T> intersect(Set<T> left, Iterable<T> right) {
11331         return (Set<T>) intersect((Collection<T>) left, asCollection(right));
11332     }
11333 
11334     /**
11335      * Create a SortedSet composed of the intersection of a SortedSet and an Iterable.  Any
11336      * elements that exist in both iterables are added to the resultant collection.
11337      * <pre class="groovyTestCase">assert [4,5] as SortedSet == ([1,2,3,4,5] as SortedSet).intersect([4,5,6,7,8])</pre>
11338      *
11339      * @param left  a SortedSet
11340      * @param right an Iterable
11341      * @return a Set as an intersection of a SortedSet and an Iterable
11342      * @since 2.4.0
11343      */
11344     public static <T> SortedSet<T> intersect(SortedSet<T> left, Iterable<T> right) {
11345         return (SortedSet<T>) intersect((Collection<T>) left, asCollection(right));
11346     }
11347 
11348     /**
11349      * Create a Map composed of the intersection of both maps.
11350      * Any entries that exist in both maps are added to the resultant map.
11351      * <pre class="groovyTestCase">assert [4:4,5:5] == [1:1,2:2,3:3,4:4,5:5].intersect([4:4,5:5,6:6,7:7,8:8])</pre>
11352      * <pre class="groovyTestCase">assert [1: 1, 2: 2, 3: 3, 4: 4].intersect( [1: 1.0, 2: 2, 5: 5] ) == [1:1, 2:2]</pre>
11353      *
11354      * @param left     a map
11355      * @param right    a map
11356      * @return a Map as an intersection of both maps
11357      * @since 1.7.4
11358      */
11359     public static <K,V> Map<K,V> intersect(Map<K,V> left, Map<K,V> right) {
11360         final Map<K,V> ansMap = createSimilarMap(left);
11361         if (right != null && right.size() > 0) {
11362             for (Map.Entry<K, V> e1 : left.entrySet()) {
11363                 for (Map.Entry<K, V> e2 : right.entrySet()) {
11364                     if (DefaultTypeTransformation.compareEqual(e1, e2)) {
11365                         ansMap.put(e1.getKey(), e1.getValue());
11366                     }
11367                 }
11368             }
11369         }
11370         return ansMap;
11371     }
11372 
11373     /**
11374      * Returns <code>true</code> if the intersection of two iterables is empty.
11375      * <pre class="groovyTestCase">assert [1,2,3].disjoint([3,4,5]) == false</pre>
11376      * <pre class="groovyTestCase">assert [1,2].disjoint([3,4]) == true</pre>
11377      *
11378      * @param left  an Iterable
11379      * @param right an Iterable
11380      * @return boolean   <code>true</code> if the intersection of two iterables
11381      *         is empty, <code>false</code> otherwise.
11382      * @since 2.4.0
11383      */
11384     public static boolean disjoint(Iterable left, Iterable right) {
11385         Collection leftCol = asCollection(left);
11386         Collection rightCol = asCollection(right);
11387 
11388         if (leftCol.isEmpty() || rightCol.isEmpty())
11389             return true;
11390 
11391         Collection pickFrom = new TreeSet(new NumberAwareComparator());
11392         pickFrom.addAll(rightCol);
11393 
11394         for (final Object o : leftCol) {
11395             if (pickFrom.contains(o))
11396                 return false;
11397         }
11398         return true;
11399     }
11400 
11401     /**
11402      * @deprecated use the Iterable variant instead
11403      * @see #disjoint(Iterable, Iterable)
11404      * @since 1.0
11405      */
11406     @Deprecated
11407     public static boolean disjoint(Collection left, Collection right) {
11408         return disjoint((Iterable) left, (Iterable) right);
11409     }
11410 
11411     /**
11412      * Compare the contents of this array to the contents of the given array.
11413      *
11414      * @param left  an int array
11415      * @param right the array being compared
11416      * @return true if the contents of both arrays are equal.
11417      * @since 1.5.0
11418      */
11419     public static boolean equals(int[] left, int[] right) {
11420         if (left == null) {
11421             return right == null;
11422         }
11423         if (right == null) {
11424             return false;
11425         }
11426         if (left == right) {
11427             return true;
11428         }
11429         if (left.length != right.length) {
11430             return false;
11431         }
11432         for (int i = 0; i < left.length; i++) {
11433             if (left[i] != right[i]) return false;
11434         }
11435         return true;
11436     }
11437 
11438     /**
11439      * Determines if the contents of this array are equal to the
11440      * contents of the given list, in the same order.  This returns
11441      * <code>false</code> if either collection is <code>null</code>.
11442      *
11443      * @param left  an array
11444      * @param right the List being compared
11445      * @return true if the contents of both collections are equal
11446      * @since 1.5.0
11447      */
11448     public static boolean equals(Object[] left, List right) {
11449         return coercedEquals(left, right);
11450     }
11451 
11452     /**
11453      * Determines if the contents of this list are equal to the
11454      * contents of the given array in the same order.  This returns
11455      * <code>false</code> if either collection is <code>null</code>.
11456      * <pre class="groovyTestCase">assert [1, "a"].equals( [ 1, "a" ] as Object[] )</pre>
11457      *
11458      * @param left  a List
11459      * @param right the Object[] being compared to
11460      * @return true if the contents of both collections are equal
11461      * @since 1.5.0
11462      */
11463     public static boolean equals(List left, Object[] right) {
11464         return coercedEquals(right, left);
11465     }
11466 
11467     private static boolean coercedEquals(Object[] left, List right) {
11468         if (left == null) {
11469             return right == null;
11470         }
11471         if (right == null) {
11472             return false;
11473         }
11474         if (left.length != right.size()) {
11475             return false;
11476         }
11477         for (int i = left.length - 1; i >= 0; i--) {
11478             final Object o1 = left[i];
11479             final Object o2 = right.get(i);
11480             if (o1 == null) {
11481                 if (o2 != null) return false;
11482             } else if (!coercedEquals(o1, o2)) {
11483                 return false;
11484             }
11485         }
11486         return true;
11487     }
11488 
11489     private static boolean coercedEquals(Object o1, Object o2) {
11490         if (o1 instanceof Comparable) {
11491             if (!(o2 instanceof Comparable && numberAwareCompareTo((Comparable) o1, (Comparable) o2) == 0)) {
11492                 return false;
11493             }
11494         }
11495         return DefaultTypeTransformation.compareEqual(o1, o2);
11496     }
11497 
11498     /**
11499      * Compare the contents of two Lists.  Order matters.
11500      * If numbers exist in the Lists, then they are compared as numbers,
11501      * for example 2 == 2L. If both lists are <code>null</code>, the result
11502      * is true; otherwise if either list is <code>null</code>, the result
11503      * is <code>false</code>.
11504      * <pre class="groovyTestCase">assert ["a", 2].equals(["a", 2])
11505      * assert ![2, "a"].equals("a", 2)
11506      * assert [2.0, "a"].equals(2L, "a") // number comparison at work</pre>
11507      *
11508      * @param left  a List
11509      * @param right the List being compared to
11510      * @return boolean   <code>true</code> if the contents of both lists are identical,
11511      *         <code>false</code> otherwise.
11512      * @since 1.0
11513      */
11514     public static boolean equals(List left, List right) {
11515         if (left == null) {
11516             return right == null;
11517         }
11518         if (right == null) {
11519             return false;
11520         }
11521         if (left == right) {
11522             return true;
11523         }
11524         if (left.size() != right.size()) {
11525             return false;
11526         }
11527         final Iterator it1 = left.iterator(), it2 = right.iterator();
11528         while (it1.hasNext()) {
11529             final Object o1 = it1.next();
11530             final Object o2 = it2.next();
11531             if (o1 == null) {
11532                 if (o2 != null) return false;
11533             } else if (!coercedEquals(o1, o2)) {
11534                 return false;
11535             }
11536         }
11537         return true;
11538     }
11539 
11540     /**
11541      * Compare the contents of two Sets for equality using Groovy's coercion rules.
11542      * <p>
11543      * Returns <tt>true</tt> if the two sets have the same size, and every member
11544      * of the specified set is contained in this set (or equivalently, every member
11545      * of this set is contained in the specified set).
11546      * If numbers exist in the sets, then they are compared as numbers,
11547      * for example 2 == 2L.  If both sets are <code>null</code>, the result
11548      * is true; otherwise if either set is <code>null</code>, the result
11549      * is <code>false</code>. Example usage:
11550      * <pre class="groovyTestCase">
11551      * Set s1 = ["a", 2]
11552      * def s2 = [2, 'a'] as Set
11553      * Set s3 = [3, 'a']
11554      * def s4 = [2.0, 'a'] as Set
11555      * def s5 = [2L, 'a'] as Set
11556      * assert s1.equals(s2)
11557      * assert !s1.equals(s3)
11558      * assert s1.equals(s4)
11559      * assert s1.equals(s5)</pre>
11560      *
11561      * @param self  a Set
11562      * @param other the Set being compared to
11563      * @return <tt>true</tt> if the contents of both sets are identical
11564      * @since 1.8.0
11565      */
11566     public static <T> boolean equals(Set<T> self, Set<T> other) {
11567         if (self == null) {
11568             return other == null;
11569         }
11570         if (other == null) {
11571             return false;
11572         }
11573         if (self == other) {
11574             return true;
11575         }
11576         if (self.size() != other.size()) {
11577             return false;
11578         }
11579         final Iterator<T> it1 = self.iterator();
11580         Collection<T> otherItems = new HashSet<T>(other);
11581         while (it1.hasNext()) {
11582             final Object o1 = it1.next();
11583             final Iterator<T> it2 = otherItems.iterator();
11584             T foundItem = null;
11585             boolean found = false;
11586             while (it2.hasNext() && foundItem == null) {
11587                 final T o2 = it2.next();
11588                 if (coercedEquals(o1, o2)) {
11589                     foundItem = o2;
11590                     found = true;
11591                 }
11592             }
11593             if (!found) return false;
11594             otherItems.remove(foundItem);
11595         }
11596         return otherItems.size() == 0;
11597     }
11598 
11599     /**
11600      * Compares two Maps treating coerced numerical values as identical.
11601      * <p>
11602      * Example usage:
11603      * <pre class="groovyTestCase">assert [a:2, b:3] == [a:2L, b:3.0]</pre>
11604      *
11605      * @param self  this Map
11606      * @param other the Map being compared to
11607      * @return <tt>true</tt> if the contents of both maps are identical
11608      * @since 1.8.0
11609      */
11610     public static boolean equals(Map self, Map other) {
11611         if (self == null) {
11612             return other == null;
11613         }
11614         if (other == null) {
11615             return false;
11616         }
11617         if (self == other) {
11618             return true;
11619         }
11620         if (self.size() != other.size()) {
11621             return false;
11622         }
11623         if (!self.keySet().equals(other.keySet())) {
11624             return false;
11625         }
11626         for (Object key : self.keySet()) {
11627             if (!coercedEquals(self.get(key), other.get(key))) {
11628                 return false;
11629             }
11630         }
11631         return true;
11632     }
11633 
11634     /**
11635      * Create a Set composed of the elements of the first Set minus the
11636      * elements of the given Collection.
11637      *
11638      * @param self     a Set object
11639      * @param removeMe the items to remove from the Set
11640      * @return the resulting Set
11641      * @since 1.5.0
11642      */
11643     public static <T> Set<T> minus(Set<T> self, Collection<?> removeMe) {
11644         Comparator comparator = (self instanceof SortedSet) ? ((SortedSet) self).comparator() : null;
11645         final Set<T> ansSet = createSimilarSet(self);
11646         ansSet.addAll(self);
11647         if (removeMe != null) {
11648             for (T o1 : self) {
11649                 for (Object o2 : removeMe) {
11650                     boolean areEqual = (comparator != null) ? (comparator.compare(o1, o2) == 0) : coercedEquals(o1, o2);
11651                     if (areEqual) {
11652                         ansSet.remove(o1);
11653                     }
11654                 }
11655             }
11656         }
11657         return ansSet;
11658     }
11659 
11660     /**
11661      * Create a Set composed of the elements of the first Set minus the
11662      * elements from the given Iterable.
11663      *
11664      * @param self     a Set object
11665      * @param removeMe the items to remove from the Set
11666      * @return the resulting Set
11667      * @since 1.8.7
11668      */
11669     public static <T> Set<T> minus(Set<T> self, Iterable<?> removeMe) {
11670         return minus(self, asCollection(removeMe));
11671     }
11672 
11673     /**
11674      * Create a Set composed of the elements of the first Set minus the given element.
11675      *
11676      * @param self     a Set object
11677      * @param removeMe the element to remove from the Set
11678      * @return the resulting Set
11679      * @since 1.5.0
11680      */
11681     public static <T> Set<T> minus(Set<T> self, Object removeMe) {
11682         Comparator comparator = (self instanceof SortedSet) ? ((SortedSet) self).comparator() : null;
11683         final Set<T> ansSet = createSimilarSet(self);
11684         for (T t : self) {
11685             boolean areEqual = (comparator != null)? (comparator.compare(t, removeMe) == 0) : coercedEquals(t, removeMe);
11686             if (!areEqual) ansSet.add(t);
11687         }
11688         return ansSet;
11689     }
11690 
11691     /**
11692      * Create a SortedSet composed of the elements of the first SortedSet minus the
11693      * elements of the given Collection.
11694      *
11695      * @param self     a SortedSet object
11696      * @param removeMe the items to remove from the SortedSet
11697      * @return the resulting SortedSet
11698      * @since 2.4.0
11699      */
11700     public static <T> SortedSet<T> minus(SortedSet<T> self, Collection<?> removeMe) {
11701         return (SortedSet<T>) minus((Set<T>) self, removeMe);
11702     }
11703 
11704     /**
11705      * Create a SortedSet composed of the elements of the first SortedSet minus the
11706      * elements of the given Iterable.
11707      *
11708      * @param self     a SortedSet object
11709      * @param removeMe the items to remove from the SortedSet
11710      * @return the resulting SortedSet
11711      * @since 2.4.0
11712      */
11713     public static <T> SortedSet<T> minus(SortedSet<T> self, Iterable<?> removeMe) {
11714         return (SortedSet<T>) minus((Set<T>) self, removeMe);
11715     }
11716 
11717     /**
11718      * Create a SortedSet composed of the elements of the first SortedSet minus the given element.
11719      *
11720      * @param self     a SortedSet object
11721      * @param removeMe the element to remove from the SortedSet
11722      * @return the resulting SortedSet
11723      * @since 2.4.0
11724      */
11725     public static <T> SortedSet<T> minus(SortedSet<T> self, Object removeMe) {
11726         return (SortedSet<T>) minus((Set<T>) self, removeMe);
11727     }
11728 
11729     /**
11730      * Create an array composed of the elements of the first array minus the
11731      * elements of the given Iterable.
11732      *
11733      * @param self     an array
11734      * @param removeMe a Collection of elements to remove
11735      * @return an array with the supplied elements removed
11736      * @since 1.5.5
11737      */
11738     @SuppressWarnings("unchecked")
11739     public static <T> T[] minus(T[] self, Iterable removeMe) {
11740         return (T[]) minus(toList(self), removeMe).toArray();
11741     }
11742 
11743     /**
11744      * Create an array composed of the elements of the first array minus the
11745      * elements of the given array.
11746      *
11747      * @param self     an array
11748      * @param removeMe an array of elements to remove
11749      * @return an array with the supplied elements removed
11750      * @since 1.5.5
11751      */
11752     @SuppressWarnings("unchecked")
11753     public static <T> T[] minus(T[] self, Object[] removeMe) {
11754         return (T[]) minus(toList(self), toList(removeMe)).toArray();
11755     }
11756 
11757     /**
11758      * Create a List composed of the elements of the first list minus
11759      * every occurrence of elements of the given Collection.
11760      * <pre class="groovyTestCase">assert [1, "a", true, true, false, 5.3] - [true, 5.3] == [1, "a", false]</pre>
11761      *
11762      * @param self     a List
11763      * @param removeMe a Collection of elements to remove
11764      * @return a List with the given elements removed
11765      * @since 1.0
11766      */
11767     public static <T> List<T> minus(List<T> self, Collection<?> removeMe) {
11768         return (List<T>) minus((Collection<T>) self, removeMe);
11769     }
11770 
11771     /**
11772      * Create a new Collection composed of the elements of the first Collection minus
11773      * every occurrence of elements of the given Collection.
11774      * <pre class="groovyTestCase">assert [1, "a", true, true, false, 5.3] - [true, 5.3] == [1, "a", false]</pre>
11775      *
11776      * @param self     a Collection
11777      * @param removeMe a Collection of elements to remove
11778      * @return a Collection with the given elements removed
11779      * @since 2.4.0
11780      */
11781     public static <T> Collection<T> minus(Collection<T> self, Collection<?> removeMe) {
11782         Collection<T> ansCollection = createSimilarCollection(self);
11783         if (self.size() == 0)
11784             return ansCollection;
11785         T head = self.iterator().next();
11786 
11787         boolean nlgnSort = sameType(new Collection[]{self, removeMe});
11788 
11789         // We can't use the same tactic as for intersection
11790         // since AbstractCollection only does a remove on the first
11791         // element it encounters.
11792 
11793         Comparator<T> numberComparator = new NumberAwareComparator<T>();
11794 
11795         if (nlgnSort && (head instanceof Comparable)) {
11796             //n*LOG(n) version
11797             Set<T> answer;
11798             if (Number.class.isInstance(head)) {
11799                 answer = new TreeSet<T>(numberComparator);
11800                 answer.addAll(self);
11801                 for (T t : self) {
11802                     if (Number.class.isInstance(t)) {
11803                         for (Object t2 : removeMe) {
11804                             if (Number.class.isInstance(t2)) {
11805                                 if (numberComparator.compare(t, (T)t2) == 0)
11806                                     answer.remove(t);
11807                             }
11808                         }
11809                     } else {
11810                         if (removeMe.contains(t))
11811                             answer.remove(t);
11812                     }
11813                 }
11814             } else {
11815                 answer = new TreeSet<T>(numberComparator);
11816                 answer.addAll(self);
11817                 answer.removeAll(removeMe);
11818             }
11819 
11820             for (T o : self) {
11821                 if (answer.contains(o))
11822                     ansCollection.add(o);
11823             }
11824         } else {
11825             //n*n version
11826             List<T> tmpAnswer = new LinkedList<T>(self);
11827             for (Iterator<T> iter = tmpAnswer.iterator(); iter.hasNext();) {
11828                 T element = iter.next();
11829                 boolean elementRemoved = false;
11830                 for (Iterator<?> iterator = removeMe.iterator(); iterator.hasNext() && !elementRemoved;) {
11831                     Object elt = iterator.next();
11832                     if (DefaultTypeTransformation.compareEqual(element, elt)) {
11833                         iter.remove();
11834                         elementRemoved = true;
11835                     }
11836                 }
11837             }
11838 
11839             //remove duplicates
11840             //can't use treeset since the base classes are different
11841             ansCollection.addAll(tmpAnswer);
11842         }
11843         return ansCollection;
11844     }
11845 
11846     /**
11847      * Create a new List composed of the elements of the first List minus
11848      * every occurrence of elements of the given Iterable.
11849      * <pre class="groovyTestCase">assert [1, "a", true, true, false, 5.3] - [true, 5.3] == [1, "a", false]</pre>
11850      *
11851      * @param self     a List
11852      * @param removeMe a Iterable of elements to remove
11853      * @return a new List with the given elements removed
11854      * @since 1.8.7
11855      */
11856     public static <T> List<T> minus(List<T> self, Iterable<?> removeMe) {
11857         return (List<T>) minus((Iterable<T>) self, removeMe);
11858     }
11859 
11860     /**
11861      * Create a new Collection composed of the elements of the first Iterable minus
11862      * every occurrence of elements of the given Iterable.
11863      * <pre class="groovyTestCase">
11864      * assert [1, "a", true, true, false, 5.3] - [true, 5.3] == [1, "a", false]
11865      * </pre>
11866      *
11867      * @param self     an Iterable
11868      * @param removeMe an Iterable of elements to remove
11869      * @return a new Collection with the given elements removed
11870      * @since 2.4.0
11871      */
11872     public static <T> Collection<T> minus(Iterable<T> self, Iterable<?> removeMe) {
11873         return minus(asCollection(self), asCollection(removeMe));
11874     }
11875 
11876     /**
11877      * Create a new List composed of the elements of the first List minus every occurrence of the
11878      * given element to remove.
11879      * <pre class="groovyTestCase">assert ["a", 5, 5, true] - 5 == ["a", true]</pre>
11880      *
11881      * @param self     a List object
11882      * @param removeMe an element to remove from the List
11883      * @return the resulting List with the given element removed
11884      * @since 1.0
11885      */
11886     public static <T> List<T> minus(List<T> self, Object removeMe) {
11887         return (List<T>) minus((Iterable<T>) self, removeMe);
11888     }
11889 
11890     /**
11891      * Create a new Collection composed of the elements of the first Iterable minus every occurrence of the
11892      * given element to remove.
11893      * <pre class="groovyTestCase">assert ["a", 5, 5, true] - 5 == ["a", true]</pre>
11894      *
11895      * @param self     an Iterable object
11896      * @param removeMe an element to remove from the Iterable
11897      * @return the resulting Collection with the given element removed
11898      * @since 2.4.0
11899      */
11900     public static <T> Collection<T> minus(Iterable<T> self, Object removeMe) {
11901         Collection<T> ansList = createSimilarCollection(self);
11902         for (T t : self) {
11903             if (!coercedEquals(t, removeMe)) ansList.add(t);
11904         }
11905         return ansList;
11906     }
11907 
11908     /**
11909      * Create a new object array composed of the elements of the first array
11910      * minus the element to remove.
11911      *
11912      * @param self    an array
11913      * @param removeMe an element to remove from the array
11914      * @return a new array with the operand removed
11915      * @since 1.5.5
11916      */
11917     @SuppressWarnings("unchecked")
11918     public static <T> T[] minus(T[] self, Object removeMe) {
11919         return (T[]) minus((Iterable<T>) toList(self), removeMe).toArray();
11920     }
11921 
11922     /**
11923      * Create a Map composed of the entries of the first map minus the
11924      * entries of the given map.
11925      *
11926      * @param self     a map object
11927      * @param removeMe the entries to remove from the map
11928      * @return the resulting map
11929      * @since 1.7.4
11930      */
11931     public static <K,V> Map<K,V> minus(Map<K,V> self, Map removeMe) {
11932         final Map<K,V> ansMap = createSimilarMap(self);
11933         ansMap.putAll(self);
11934         if (removeMe != null && removeMe.size() > 0) {
11935             for (Map.Entry<K, V> e1 : self.entrySet()) {
11936                 for (Object e2 : removeMe.entrySet()) {
11937                     if (DefaultTypeTransformation.compareEqual(e1, e2)) {
11938                         ansMap.remove(e1.getKey());
11939                     }
11940                 }
11941             }
11942         }
11943         return ansMap;
11944     }
11945 
11946     /**
11947      * Flatten a Collection.  This Collection and any nested arrays or
11948      * collections have their contents (recursively) added to the new collection.
11949      * <pre class="groovyTestCase">assert [1,2,3,4,5] == [1,[2,3],[[4]],[],5].flatten()</pre>
11950      *
11951      * @param self a Collection to flatten
11952      * @return a flattened Collection
11953      * @since 1.6.0
11954      */
11955     public static Collection<?> flatten(Collection<?> self) {
11956         return flatten(self, createSimilarCollection(self));
11957     }
11958 
11959     /**
11960      * Flatten an Iterable.  This Iterable and any nested arrays or
11961      * collections have their contents (recursively) added to the new collection.
11962      * <pre class="groovyTestCase">assert [1,2,3,4,5] == [1,[2,3],[[4]],[],5].flatten()</pre>
11963      *
11964      * @param self a Iterable to flatten
11965      * @return a flattened Collection
11966      * @since 1.6.0
11967      */
11968     public static Collection<?> flatten(Iterable<?> self) {
11969         return flatten(self, createSimilarCollection(self));
11970     }
11971 
11972     /**
11973      * Flatten a List.  This List and any nested arrays or
11974      * collections have their contents (recursively) added to the new List.
11975      * <pre class="groovyTestCase">assert [1,2,3,4,5] == [1,[2,3],[[4]],[],5].flatten()</pre>
11976      *
11977      * @param self a List to flatten
11978      * @return a flattened List
11979      * @since 2.4.0
11980      */
11981     public static List<?> flatten(List<?> self) {
11982         return (List<?>) flatten((Collection<?>) self);
11983     }
11984 
11985     /**
11986      * Flatten a Set.  This Set and any nested arrays or
11987      * collections have their contents (recursively) added to the new Set.
11988      * <pre class="groovyTestCase">assert [1,2,3,4,5] as Set == ([1,[2,3],[[4]],[],5] as Set).flatten()</pre>
11989      *
11990      * @param self a Set to flatten
11991      * @return a flattened Set
11992      * @since 2.4.0
11993      */
11994     public static Set<?> flatten(Set<?> self) {
11995         return (Set<?>) flatten((Collection<?>) self);
11996     }
11997 
11998     /**
11999      * Flatten a SortedSet.  This SortedSet and any nested arrays or
12000      * collections have their contents (recursively) added to the new SortedSet.
12001      * <pre class="groovyTestCase">assert [1,2,3,4,5] as SortedSet == ([1,[2,3],[[4]],[],5] as SortedSet).flatten()</pre>
12002      *
12003      * @param self a SortedSet to flatten
12004      * @return a flattened SortedSet
12005      * @since 2.4.0
12006      */
12007     public static SortedSet<?> flatten(SortedSet<?> self) {
12008         return (SortedSet<?>) flatten((Collection<?>) self);
12009     }
12010 
12011     /**
12012      * Flatten an array.  This array and any nested arrays or
12013      * collections have their contents (recursively) added to the new collection.
12014      *
12015      * @param self an Array to flatten
12016      * @return a flattened Collection
12017      * @since 1.6.0
12018      */
12019     public static Collection flatten(Object[] self) {
12020         return flatten(toList(self), new ArrayList());
12021     }
12022 
12023     /**
12024      * Flatten an array.  This array and any nested arrays or
12025      * collections have their contents (recursively) added to the new collection.
12026      *
12027      * @param self a boolean Array to flatten
12028      * @return a flattened Collection
12029      * @since 1.6.0
12030      */
12031     public static Collection flatten(boolean[] self) {
12032         return flatten(toList(self), new ArrayList());
12033     }
12034 
12035     /**
12036      * Flatten an array.  This array and any nested arrays or
12037      * collections have their contents (recursively) added to the new collection.
12038      *
12039      * @param self a byte Array to flatten
12040      * @return a flattened Collection
12041      * @since 1.6.0
12042      */
12043     public static Collection flatten(byte[] self) {
12044         return flatten(toList(self), new ArrayList());
12045     }
12046 
12047     /**
12048      * Flatten an array.  This array and any nested arrays or
12049      * collections have their contents (recursively) added to the new collection.
12050      *
12051      * @param self a char Array to flatten
12052      * @return a flattened Collection
12053      * @since 1.6.0
12054      */
12055     public static Collection flatten(char[] self) {
12056         return flatten(toList(self), new ArrayList());
12057     }
12058 
12059     /**
12060      * Flatten an array.  This array and any nested arrays or
12061      * collections have their contents (recursively) added to the new collection.
12062      *
12063      * @param self a short Array to flatten
12064      * @return a flattened Collection
12065      * @since 1.6.0
12066      */
12067     public static Collection flatten(short[] self) {
12068         return flatten(toList(self), new ArrayList());
12069     }
12070 
12071     /**
12072      * Flatten an array.  This array and any nested arrays or
12073      * collections have their contents (recursively) added to the new collection.
12074      *
12075      * @param self an int Array to flatten
12076      * @return a flattened Collection
12077      * @since 1.6.0
12078      */
12079     public static Collection flatten(int[] self) {
12080         return flatten(toList(self), new ArrayList());
12081     }
12082 
12083     /**
12084      * Flatten an array.  This array and any nested arrays or
12085      * collections have their contents (recursively) added to the new collection.
12086      *
12087      * @param self a long Array to flatten
12088      * @return a flattened Collection
12089      * @since 1.6.0
12090      */
12091     public static Collection flatten(long[] self) {
12092         return flatten(toList(self), new ArrayList());
12093     }
12094 
12095     /**
12096      * Flatten an array.  This array and any nested arrays or
12097      * collections have their contents (recursively) added to the new collection.
12098      *
12099      * @param self a float Array to flatten
12100      * @return a flattened Collection
12101      * @since 1.6.0
12102      */
12103     public static Collection flatten(float[] self) {
12104         return flatten(toList(self), new ArrayList());
12105     }
12106 
12107     /**
12108      * Flatten an array.  This array and any nested arrays or
12109      * collections have their contents (recursively) added to the new collection.
12110      *
12111      * @param self a double Array to flatten
12112      * @return a flattened Collection
12113      * @since 1.6.0
12114      */
12115     public static Collection flatten(double[] self) {
12116         return flatten(toList(self), new ArrayList());
12117     }
12118 
12119     private static Collection flatten(Iterable elements, Collection addTo) {
12120         for (Object element : elements) {
12121             if (element instanceof Collection) {
12122                 flatten((Collection) element, addTo);
12123             } else if (element != null && element.getClass().isArray()) {
12124                 flatten(DefaultTypeTransformation.arrayAsCollection(element), addTo);
12125             } else {
12126                 // found a leaf
12127                 addTo.add(element);
12128             }
12129         }
12130         return addTo;
12131     }
12132 
12133     /**
12134      * @deprecated Use the Iterable version of flatten instead
12135      * @see #flatten(Iterable, Closure)
12136      * @since 1.6.0
12137      */
12138     @Deprecated
12139     public static <T> Collection<T> flatten(Collection<T> self, Closure<? extends T> flattenUsing) {
12140         return flatten(self, createSimilarCollection(self), flattenUsing);
12141     }
12142 
12143     /**
12144      * Flatten an Iterable.  This Iterable and any nested arrays or
12145      * collections have their contents (recursively) added to the new collection.
12146      * For any non-Array, non-Collection object which represents some sort
12147      * of collective type, the supplied closure should yield the contained items;
12148      * otherwise, the closure should just return any element which corresponds to a leaf.
12149      *
12150      * @param self an Iterable
12151      * @param flattenUsing a closure to determine how to flatten non-Array, non-Collection elements
12152      * @return a flattened Collection
12153      * @since 1.6.0
12154      */
12155     public static <T> Collection<T> flatten(Iterable<T> self, Closure<? extends T> flattenUsing) {
12156         return flatten(self, createSimilarCollection(self), flattenUsing);
12157     }
12158 
12159     private static <T> Collection<T> flatten(Iterable elements, Collection<T> addTo, Closure<? extends T> flattenUsing) {
12160         for (Object element : elements) {
12161             if (element instanceof Collection) {
12162                 flatten((Collection) element, addTo, flattenUsing);
12163             } else if (element != null && element.getClass().isArray()) {
12164                 flatten(DefaultTypeTransformation.arrayAsCollection(element), addTo, flattenUsing);
12165             } else {
12166                 T flattened = flattenUsing.call(new Object[]{element});
12167                 boolean returnedSelf = flattened == element;
12168                 if (!returnedSelf && flattened instanceof Collection) {
12169                     List<?> list = toList((Iterable<?>) flattened);
12170                     if (list.size() == 1 && list.get(0) == element) {
12171                         returnedSelf = true;
12172                     }
12173                 }
12174                 if (flattened instanceof Collection && !returnedSelf) {
12175                     flatten((Collection) flattened, addTo, flattenUsing);
12176                 } else {
12177                     addTo.add(flattened);
12178                 }
12179             }
12180         }
12181         return addTo;
12182     }
12183 
12184     /**
12185      * Overloads the left shift operator to provide an easy way to append
12186      * objects to a Collection.
12187      * <pre class="groovyTestCase">def list = [1,2]
12188      * list &lt;&lt; 3
12189      * assert list == [1,2,3]</pre>
12190      *
12191      * @param self  a Collection
12192      * @param value an Object to be added to the collection.
12193      * @return same collection, after the value was added to it.
12194      * @since 1.0
12195      */
12196     public static <T> Collection<T> leftShift(Collection<T> self, T value) {
12197         self.add(value);
12198         return self;
12199     }
12200 
12201     /**
12202      * Overloads the left shift operator to provide an easy way to append
12203      * objects to a List.
12204      * <pre class="groovyTestCase">def list = [1,2]
12205      * list &lt;&lt; 3
12206      * assert list == [1,2,3]</pre>
12207      *
12208      * @param self  a List
12209      * @param value an Object to be added to the List.
12210      * @return same List, after the value was added to it.
12211      * @since 2.4.0
12212      */
12213     public static <T> List<T> leftShift(List<T> self, T value) {
12214         return (List<T>) leftShift((Collection<T>) self, value);
12215     }
12216 
12217     /**
12218      * Overloads the left shift operator to provide an easy way to append
12219      * objects to a Set.
12220      * <pre class="groovyTestCase">def set = [1,2] as Set
12221      * set &lt;&lt; 3
12222      * assert set == [1,2,3] as Set</pre>
12223      *
12224      * @param self  a Set
12225      * @param value an Object to be added to the Set.
12226      * @return same Set, after the value was added to it.
12227      * @since 2.4.0
12228      */
12229     public static <T> Set<T> leftShift(Set<T> self, T value) {
12230         return (Set<T>) leftShift((Collection<T>) self, value);
12231     }
12232 
12233     /**
12234      * Overloads the left shift operator to provide an easy way to append
12235      * objects to a SortedSet.
12236      * <pre class="groovyTestCase">def set = [1,2] as SortedSet
12237      * set &lt;&lt; 3
12238      * assert set == [1,2,3] as SortedSet</pre>
12239      *
12240      * @param self  a SortedSet
12241      * @param value an Object to be added to the SortedSet.
12242      * @return same SortedSet, after the value was added to it.
12243      * @since 2.4.0
12244      */
12245     public static <T> SortedSet<T> leftShift(SortedSet<T> self, T value) {
12246         return (SortedSet<T>) leftShift((Collection<T>) self, value);
12247     }
12248 
12249     /**
12250      * Overloads the left shift operator to provide an easy way to append
12251      * objects to a BlockingQueue.
12252      * In case of bounded queue the method will block till space in the queue become available
12253      * <pre class="groovyTestCase">def list = new java.util.concurrent.LinkedBlockingQueue ()
12254      * list &lt;&lt; 3 &lt;&lt; 2 &lt;&lt; 1
12255      * assert list.iterator().collect{it} == [3,2,1]</pre>
12256      *
12257      * @param self  a Collection
12258      * @param value an Object to be added to the collection.
12259      * @return same collection, after the value was added to it.
12260      * @since 1.7.1
12261      */
12262     public static <T> BlockingQueue<T> leftShift(BlockingQueue<T> self, T value) throws InterruptedException {
12263         self.put(value);
12264         return self;
12265     }
12266 
12267     /**
12268      * Overloads the left shift operator to provide an easy way to append
12269      * Map.Entry values to a Map.
12270      *
12271      * @param self  a Map
12272      * @param entry a Map.Entry to be added to the Map.
12273      * @return same map, after the value has been added to it.
12274      * @since 1.6.0
12275      */
12276     public static <K, V> Map<K, V> leftShift(Map<K, V> self, Map.Entry<K, V> entry) {
12277         self.put(entry.getKey(), entry.getValue());
12278         return self;
12279     }
12280 
12281     /**
12282      * Overloads the left shift operator to provide an easy way to put
12283      * one maps entries into another map. This allows the compact syntax
12284      * <code>map1 &lt;&lt; map2</code>; otherwise it's just a synonym for
12285      * <code>putAll</code> though it returns the original map rather than
12286      * being a <code>void</code> method. Example usage:
12287      * <pre class="groovyTestCase">def map = [a:1, b:2]
12288      * map &lt;&lt; [c:3, d:4]
12289      * assert map == [a:1, b:2, c:3, d:4]</pre>
12290      *
12291      * @param self  a Map
12292      * @param other another Map whose entries should be added to the original Map.
12293      * @return same map, after the values have been added to it.
12294      * @since 1.7.2
12295      */
12296     public static <K, V> Map<K, V> leftShift(Map<K, V> self, Map<K, V> other) {
12297         self.putAll(other);
12298         return self;
12299     }
12300 
12301     /**
12302      * Implementation of the left shift operator for integral types.  Non integral
12303      * Number types throw UnsupportedOperationException.
12304      *
12305      * @param self    a Number object
12306      * @param operand the shift distance by which to left shift the number
12307      * @return the resulting number
12308      * @since 1.5.0
12309      */
12310     public static Number leftShift(Number self, Number operand) {
12311         return NumberMath.leftShift(self, operand);
12312     }
12313 
12314     /**
12315      * Implementation of the right shift operator for integral types.  Non integral
12316      * Number types throw UnsupportedOperationException.
12317      *
12318      * @param self    a Number object
12319      * @param operand the shift distance by which to right shift the number
12320      * @return the resulting number
12321      * @since 1.5.0
12322      */
12323     public static Number rightShift(Number self, Number operand) {
12324         return NumberMath.rightShift(self, operand);
12325     }
12326 
12327     /**
12328      * Implementation of the right shift (unsigned) operator for integral types.  Non integral
12329      * Number types throw UnsupportedOperationException.
12330      *
12331      * @param self    a Number object
12332      * @param operand the shift distance by which to right shift (unsigned) the number
12333      * @return the resulting number
12334      * @since 1.5.0
12335      */
12336     public static Number rightShiftUnsigned(Number self, Number operand) {
12337         return NumberMath.rightShiftUnsigned(self, operand);
12338     }
12339 
12340     // Primitive type array methods
12341     //-------------------------------------------------------------------------
12342 
12343     /**
12344      * Support the subscript operator with a range for a byte array
12345      *
12346      * @param array a byte array
12347      * @param range a range indicating the indices for the items to retrieve
12348      * @return list of the retrieved bytes
12349      * @since 1.0
12350      */
12351     @SuppressWarnings("unchecked")
12352     public static List<Byte> getAt(byte[] array, Range range) {
12353         return primitiveArrayGet(array, range);
12354     }
12355 
12356     /**
12357      * Support the subscript operator with a range for a char array
12358      *
12359      * @param array a char array
12360      * @param range a range indicating the indices for the items to retrieve
12361      * @return list of the retrieved chars
12362      * @since 1.5.0
12363      */
12364     @SuppressWarnings("unchecked")
12365     public static List<Character> getAt(char[] array, Range range) {
12366         return primitiveArrayGet(array, range);
12367     }
12368 
12369     /**
12370      * Support the subscript operator with a range for a short array
12371      *
12372      * @param array a short array
12373      * @param range a range indicating the indices for the items to retrieve
12374      * @return list of the retrieved shorts
12375      * @since 1.0
12376      */
12377     @SuppressWarnings("unchecked")
12378     public static List<Short> getAt(short[] array, Range range) {
12379         return primitiveArrayGet(array, range);
12380     }
12381 
12382     /**
12383      * Support the subscript operator with a range for an int array
12384      *
12385      * @param array an int array
12386      * @param range a range indicating the indices for the items to retrieve
12387      * @return list of the ints at the given indices
12388      * @since 1.0
12389      */
12390     @SuppressWarnings("unchecked")
12391     public static List<Integer> getAt(int[] array, Range range) {
12392         return primitiveArrayGet(array, range);
12393     }
12394 
12395     /**
12396      * Support the subscript operator with a range for a long array
12397      *
12398      * @param array a long array
12399      * @param range a range indicating the indices for the items to retrieve
12400      * @return list of the retrieved longs
12401      * @since 1.0
12402      */
12403     @SuppressWarnings("unchecked")
12404     public static List<Long> getAt(long[] array, Range range) {
12405         return primitiveArrayGet(array, range);
12406     }
12407 
12408     /**
12409      * Support the subscript operator with a range for a float array
12410      *
12411      * @param array a float array
12412      * @param range a range indicating the indices for the items to retrieve
12413      * @return list of the retrieved floats
12414      * @since 1.0
12415      */
12416     @SuppressWarnings("unchecked")
12417     public static List<Float> getAt(float[] array, Range range) {
12418         return primitiveArrayGet(array, range);
12419     }
12420 
12421     /**
12422      * Support the subscript operator with a range for a double array
12423      *
12424      * @param array a double array
12425      * @param range a range indicating the indices for the items to retrieve
12426      * @return list of the retrieved doubles
12427      * @since 1.0
12428      */
12429     @SuppressWarnings("unchecked")
12430     public static List<Double> getAt(double[] array, Range range) {
12431         return primitiveArrayGet(array, range);
12432     }
12433 
12434     /**
12435      * Support the subscript operator with a range for a boolean array
12436      *
12437      * @param array a boolean array
12438      * @param range a range indicating the indices for the items to retrieve
12439      * @return list of the retrieved booleans
12440      * @since 1.0
12441      */
12442     @SuppressWarnings("unchecked")
12443     public static List<Boolean> getAt(boolean[] array, Range range) {
12444         return primitiveArrayGet(array, range);
12445     }
12446 
12447     /**
12448      * Support the subscript operator with an IntRange for a byte array
12449      *
12450      * @param array a byte array
12451      * @param range an IntRange indicating the indices for the items to retrieve
12452      * @return list of the retrieved bytes
12453      * @since 1.0
12454      */
12455     @SuppressWarnings("unchecked")
12456     public static List<Byte> getAt(byte[] array, IntRange range) {
12457         RangeInfo info = subListBorders(array.length, range);
12458         List<Byte> answer = primitiveArrayGet(array, new IntRange(true, info.from, info.to - 1));
12459         return info.reverse ? reverse(answer) : answer;
12460     }
12461 
12462     /**
12463      * Support the subscript operator with an IntRange for a char array
12464      *
12465      * @param array a char array
12466      * @param range an IntRange indicating the indices for the items to retrieve
12467      * @return list of the retrieved chars
12468      * @since 1.0
12469      */
12470     @SuppressWarnings("unchecked")
12471     public static List<Character> getAt(char[] array, IntRange range) {
12472         RangeInfo info = subListBorders(array.length, range);
12473         List<Character> answer = primitiveArrayGet(array, new IntRange(true, info.from, info.to - 1));
12474         return info.reverse ? reverse(answer) : answer;
12475     }
12476 
12477     /**
12478      * Support the subscript operator with an IntRange for a short array
12479      *
12480      * @param array a short array
12481      * @param range an IntRange indicating the indices for the items to retrieve
12482      * @return list of the retrieved shorts
12483      * @since 1.0
12484      */
12485     @SuppressWarnings("unchecked")
12486     public static List<Short> getAt(short[] array, IntRange range) {
12487         RangeInfo info = subListBorders(array.length, range);
12488         List<Short> answer = primitiveArrayGet(array, new IntRange(true, info.from, info.to - 1));
12489         return info.reverse ? reverse(answer) : answer;
12490     }
12491 
12492     /**
12493      * Support the subscript operator with an IntRange for an int array
12494      *
12495      * @param array an int array
12496      * @param range an IntRange indicating the indices for the items to retrieve
12497      * @return list of the retrieved ints
12498      * @since 1.0
12499      */
12500     @SuppressWarnings("unchecked")
12501     public static List<Integer> getAt(int[] array, IntRange range) {
12502         RangeInfo info = subListBorders(array.length, range);
12503         List<Integer> answer = primitiveArrayGet(array, new IntRange(true, info.from, info.to - 1));
12504         return info.reverse ? reverse(answer) : answer;
12505     }
12506 
12507     /**
12508      * Support the subscript operator with an IntRange for a long array
12509      *
12510      * @param array a long array
12511      * @param range an IntRange indicating the indices for the items to retrieve
12512      * @return list of the retrieved longs
12513      * @since 1.0
12514      */
12515     @SuppressWarnings("unchecked")
12516     public static List<Long> getAt(long[] array, IntRange range) {
12517         RangeInfo info = subListBorders(array.length, range);
12518         List<Long> answer = primitiveArrayGet(array, new IntRange(true, info.from, info.to - 1));
12519         return info.reverse ? reverse(answer) : answer;
12520     }
12521 
12522     /**
12523      * Support the subscript operator with an IntRange for a float array
12524      *
12525      * @param array a float array
12526      * @param range an IntRange indicating the indices for the items to retrieve
12527      * @return list of the retrieved floats
12528      * @since 1.0
12529      */
12530     @SuppressWarnings("unchecked")
12531     public static List<Float> getAt(float[] array, IntRange range) {
12532         RangeInfo info = subListBorders(array.length, range);
12533         List<Float> answer = primitiveArrayGet(array, new IntRange(true, info.from, info.to - 1));
12534         return info.reverse ? reverse(answer) : answer;
12535     }
12536 
12537     /**
12538      * Support the subscript operator with an IntRange for a double array
12539      *
12540      * @param array a double array
12541      * @param range an IntRange indicating the indices for the items to retrieve
12542      * @return list of the retrieved doubles
12543      * @since 1.0
12544      */
12545     @SuppressWarnings("unchecked")
12546     public static List<Double> getAt(double[] array, IntRange range) {
12547         RangeInfo info = subListBorders(array.length, range);
12548         List<Double> answer = primitiveArrayGet(array, new IntRange(true, info.from, info.to - 1));
12549         return info.reverse ? reverse(answer) : answer;
12550     }
12551 
12552     /**
12553      * Support the subscript operator with an IntRange for a boolean array
12554      *
12555      * @param array a boolean array
12556      * @param range an IntRange indicating the indices for the items to retrieve
12557      * @return list of the retrieved booleans
12558      * @since 1.0
12559      */
12560     @SuppressWarnings("unchecked")
12561     public static List<Boolean> getAt(boolean[] array, IntRange range) {
12562         RangeInfo info = subListBorders(array.length, range);
12563         List<Boolean> answer = primitiveArrayGet(array, new IntRange(true, info.from, info.to - 1));
12564         return info.reverse ? reverse(answer) : answer;
12565     }
12566 
12567     /**
12568      * Support the subscript operator with an ObjectRange for a byte array
12569      *
12570      * @param array a byte array
12571      * @param range an ObjectRange indicating the indices for the items to retrieve
12572      * @return list of the retrieved bytes
12573      * @since 1.0
12574      */
12575     @SuppressWarnings("unchecked")
12576     public static List<Byte> getAt(byte[] array, ObjectRange range) {
12577         return primitiveArrayGet(array, range);
12578     }
12579 
12580     /**
12581      * Support the subscript operator with an ObjectRange for a char array
12582      *
12583      * @param array a char array
12584      * @param range an ObjectRange indicating the indices for the items to retrieve
12585      * @return list of the retrieved chars
12586      * @since 1.0
12587      */
12588     @SuppressWarnings("unchecked")
12589     public static List<Character> getAt(char[] array, ObjectRange range) {
12590         return primitiveArrayGet(array, range);
12591     }
12592 
12593     /**
12594      * Support the subscript operator with an ObjectRange for a short array
12595      *
12596      * @param array a short array
12597      * @param range an ObjectRange indicating the indices for the items to retrieve
12598      * @return list of the retrieved shorts
12599      * @since 1.0
12600      */
12601     @SuppressWarnings("unchecked")
12602     public static List<Short> getAt(short[] array, ObjectRange range) {
12603         return primitiveArrayGet(array, range);
12604     }
12605 
12606     /**
12607      * Support the subscript operator with an ObjectRange for an int array
12608      *
12609      * @param array an int array
12610      * @param range an ObjectRange indicating the indices for the items to retrieve
12611      * @return list of the retrieved ints
12612      * @since 1.0
12613      */
12614     @SuppressWarnings("unchecked")
12615     public static List<Integer> getAt(int[] array, ObjectRange range) {
12616         return primitiveArrayGet(array, range);
12617     }
12618 
12619     /**
12620      * Support the subscript operator with an ObjectRange for a long array
12621      *
12622      * @param array a long array
12623      * @param range an ObjectRange indicating the indices for the items to retrieve
12624      * @return list of the retrieved longs
12625      * @since 1.0
12626      */
12627     @SuppressWarnings("unchecked")
12628     public static List<Long> getAt(long[] array, ObjectRange range) {
12629         return primitiveArrayGet(array, range);
12630     }
12631 
12632     /**
12633      * Support the subscript operator with an ObjectRange for a float array
12634      *
12635      * @param array a float array
12636      * @param range an ObjectRange indicating the indices for the items to retrieve
12637      * @return list of the retrieved floats
12638      * @since 1.0
12639      */
12640     @SuppressWarnings("unchecked")
12641     public static List<Float> getAt(float[] array, ObjectRange range) {
12642         return primitiveArrayGet(array, range);
12643     }
12644 
12645     /**
12646      * Support the subscript operator with an ObjectRange for a double array
12647      *
12648      * @param array a double array
12649      * @param range an ObjectRange indicating the indices for the items to retrieve
12650      * @return list of the retrieved doubles
12651      * @since 1.0
12652      */
12653     @SuppressWarnings("unchecked")
12654     public static List<Double> getAt(double[] array, ObjectRange range) {
12655         return primitiveArrayGet(array, range);
12656     }
12657 
12658     /**
12659      * Support the subscript operator with an ObjectRange for a byte array
12660      *
12661      * @param array a byte array
12662      * @param range an ObjectRange indicating the indices for the items to retrieve
12663      * @return list of the retrieved bytes
12664      * @since 1.0
12665      */
12666     @SuppressWarnings("unchecked")
12667     public static List<Boolean> getAt(boolean[] array, ObjectRange range) {
12668         return primitiveArrayGet(array, range);
12669     }
12670 
12671     /**
12672      * Support the subscript operator with a collection for a byte array
12673      *
12674      * @param array a byte array
12675      * @param indices a collection of indices for the items to retrieve
12676      * @return list of the bytes at the given indices
12677      * @since 1.0
12678      */
12679     @SuppressWarnings("unchecked")
12680     public static List<Byte> getAt(byte[] array, Collection indices) {
12681         return primitiveArrayGet(array, indices);
12682     }
12683 
12684     /**
12685      * Support the subscript operator with a collection for a char array
12686      *
12687      * @param array a char array
12688      * @param indices a collection of indices for the items to retrieve
12689      * @return list of the chars at the given indices
12690      * @since 1.0
12691      */
12692     @SuppressWarnings("unchecked")
12693     public static List<Character> getAt(char[] array, Collection indices) {
12694         return primitiveArrayGet(array, indices);
12695     }
12696 
12697     /**
12698      * Support the subscript operator with a collection for a short array
12699      *
12700      * @param array a short array
12701      * @param indices a collection of indices for the items to retrieve
12702      * @return list of the shorts at the given indices
12703      * @since 1.0
12704      */
12705     @SuppressWarnings("unchecked")
12706     public static List<Short> getAt(short[] array, Collection indices) {
12707         return primitiveArrayGet(array, indices);
12708     }
12709 
12710     /**
12711      * Support the subscript operator with a collection for an int array
12712      *
12713      * @param array an int array
12714      * @param indices a collection of indices for the items to retrieve
12715      * @return list of the ints at the given indices
12716      * @since 1.0
12717      */
12718     @SuppressWarnings("unchecked")
12719     public static List<Integer> getAt(int[] array, Collection indices) {
12720         return primitiveArrayGet(array, indices);
12721     }
12722 
12723     /**
12724      * Support the subscript operator with a collection for a long array
12725      *
12726      * @param array a long array
12727      * @param indices a collection of indices for the items to retrieve
12728      * @return list of the longs at the given indices
12729      * @since 1.0
12730      */
12731     @SuppressWarnings("unchecked")
12732     public static List<Long> getAt(long[] array, Collection indices) {
12733         return primitiveArrayGet(array, indices);
12734     }
12735 
12736     /**
12737      * Support the subscript operator with a collection for a float array
12738      *
12739      * @param array a float array
12740      * @param indices a collection of indices for the items to retrieve
12741      * @return list of the floats at the given indices
12742      * @since 1.0
12743      */
12744     @SuppressWarnings("unchecked")
12745     public static List<Float> getAt(float[] array, Collection indices) {
12746         return primitiveArrayGet(array, indices);
12747     }
12748 
12749     /**
12750      * Support the subscript operator with a collection for a double array
12751      *
12752      * @param array a double array
12753      * @param indices a collection of indices for the items to retrieve
12754      * @return list of the doubles at the given indices
12755      * @since 1.0
12756      */
12757     @SuppressWarnings("unchecked")
12758     public static List<Double> getAt(double[] array, Collection indices) {
12759         return primitiveArrayGet(array, indices);
12760     }
12761 
12762     /**
12763      * Support the subscript operator with a collection for a boolean array
12764      *
12765      * @param array a boolean array
12766      * @param indices a collection of indices for the items to retrieve
12767      * @return list of the booleans at the given indices
12768      * @since 1.0
12769      */
12770     @SuppressWarnings("unchecked")
12771     public static List<Boolean> getAt(boolean[] array, Collection indices) {
12772         return primitiveArrayGet(array, indices);
12773     }
12774 
12775     /**
12776      * Support the subscript operator for a Bitset
12777      *
12778      * @param self  a BitSet
12779      * @param index index to retrieve
12780      * @return value of the bit at the given index
12781      * @see java.util.BitSet
12782      * @since 1.5.0
12783      */
12784     public static boolean getAt(BitSet self, int index) {
12785         int i = normaliseIndex(index, self.length());
12786         return self.get(i);
12787     }
12788 
12789     /**
12790      * Support retrieving a subset of a BitSet using a Range
12791      *
12792      * @param self  a BitSet
12793      * @param range a Range defining the desired subset
12794      * @return a new BitSet that represents the requested subset
12795      * @see java.util.BitSet
12796      * @see groovy.lang.IntRange
12797      * @since 1.5.0
12798      */
12799     public static BitSet getAt(BitSet self, IntRange range) {
12800         RangeInfo info = subListBorders(self.length(), range);
12801         BitSet result = new BitSet();
12802 
12803         int numberOfBits = info.to - info.from;
12804         int adjuster = 1;
12805         int offset = info.from;
12806 
12807         if (info.reverse) {
12808             adjuster = -1;
12809             offset = info.to - 1;
12810         }
12811 
12812         for (int i = 0; i < numberOfBits; i++) {
12813             result.set(i, self.get(offset + (adjuster * i)));
12814         }
12815 
12816         return result;
12817     }
12818 
12819 //    public static Boolean putAt(boolean[] array, int idx, Boolean newValue) {
12820 //        return (Boolean) primitiveArrayPut(array, idx, newValue);
12821 //    }
12822 //
12823 //    public static Byte putAt(byte[] array, int idx, Object newValue) {
12824 //        if (!(newValue instanceof Byte)) {
12825 //            Number n = (Number) newValue;
12826 //            newValue = new Byte(n.byteValue());
12827 //        }
12828 //        return (Byte) primitiveArrayPut(array, idx, newValue);
12829 //    }
12830 //
12831 //    public static Character putAt(char[] array, int idx, Object newValue) {
12832 //        if (newValue instanceof String) {
12833 //            String s = (String) newValue;
12834 //            if (s.length() != 1) throw new IllegalArgumentException("String of length 1 expected but got a bigger one");
12835 //            char c = s.charAt(0);
12836 //            newValue = new Character(c);
12837 //        }
12838 //        return (Character) primitiveArrayPut(array, idx, newValue);
12839 //    }
12840 //
12841 //    public static Short putAt(short[] array, int idx, Object newValue) {
12842 //        if (!(newValue instanceof Short)) {
12843 //            Number n = (Number) newValue;
12844 //            newValue = new Short(n.shortValue());
12845 //        }
12846 //        return (Short) primitiveArrayPut(array, idx, newValue);
12847 //    }
12848 //
12849 //    public static Integer putAt(int[] array, int idx, Object newValue) {
12850 //        if (!(newValue instanceof Integer)) {
12851 //            Number n = (Number) newValue;
12852 //            newValue = Integer.valueOf(n.intValue());
12853 //        }
12854 //        array [normaliseIndex(idx,array.length)] = ((Integer)newValue).intValue();
12855 //        return (Integer) newValue;
12856 //    }
12857 //
12858 //    public static Long putAt(long[] array, int idx, Object newValue) {
12859 //        if (!(newValue instanceof Long)) {
12860 //            Number n = (Number) newValue;
12861 //            newValue = new Long(n.longValue());
12862 //        }
12863 //        return (Long) primitiveArrayPut(array, idx, newValue);
12864 //    }
12865 //
12866 //    public static Float putAt(float[] array, int idx, Object newValue) {
12867 //        if (!(newValue instanceof Float)) {
12868 //            Number n = (Number) newValue;
12869 //            newValue = new Float(n.floatValue());
12870 //        }
12871 //        return (Float) primitiveArrayPut(array, idx, newValue);
12872 //    }
12873 //
12874 //    public static Double putAt(double[] array, int idx, Object newValue) {
12875 //        if (!(newValue instanceof Double)) {
12876 //            Number n = (Number) newValue;
12877 //            newValue = new Double(n.doubleValue());
12878 //        }
12879 //        return (Double) primitiveArrayPut(array, idx, newValue);
12880 //    }
12881 
12882     /**
12883      * Support assigning a range of values with a single assignment statement.
12884      *
12885      * @param self  a BitSet
12886      * @param range the range of values to set
12887      * @param value value
12888      * @see java.util.BitSet
12889      * @see groovy.lang.Range
12890      * @since 1.5.0
12891      */
12892     public static void putAt(BitSet self, IntRange range, boolean value) {
12893         RangeInfo info = subListBorders(self.length(), range);
12894         self.set(info.from, info.to, value);
12895     }
12896 
12897     /**
12898      * Support subscript-style assignment for a BitSet.
12899      *
12900      * @param self  a BitSet
12901      * @param index index of the entry to set
12902      * @param value value
12903      * @see java.util.BitSet
12904      * @since 1.5.0
12905      */
12906     public static void putAt(BitSet self, int index, boolean value) {
12907         self.set(index, value);
12908     }
12909 
12910     /**
12911      * Allows arrays to behave similar to collections.
12912      * @param array a boolean array
12913      * @return the length of the array
12914      * @see java.lang.reflect.Array#getLength(java.lang.Object)
12915      * @since 1.5.0
12916      */
12917     public static int size(boolean[] array) {
12918         return Array.getLength(array);
12919     }
12920 
12921     /**
12922      * Allows arrays to behave similar to collections.
12923      * @param array a byte array
12924      * @return the length of the array
12925      * @see java.lang.reflect.Array#getLength(java.lang.Object)
12926      * @since 1.0
12927      */
12928     public static int size(byte[] array) {
12929         return Array.getLength(array);
12930     }
12931 
12932     /**
12933      * Allows arrays to behave similar to collections.
12934      * @param array a char array
12935      * @return the length of the array
12936      * @see java.lang.reflect.Array#getLength(java.lang.Object)
12937      * @since 1.0
12938      */
12939     public static int size(char[] array) {
12940         return Array.getLength(array);
12941     }
12942 
12943     /**
12944      * Allows arrays to behave similar to collections.
12945      * @param array a short array
12946      * @return the length of the array
12947      * @see java.lang.reflect.Array#getLength(java.lang.Object)
12948      * @since 1.0
12949      */
12950     public static int size(short[] array) {
12951         return Array.getLength(array);
12952     }
12953 
12954     /**
12955      * Allows arrays to behave similar to collections.
12956      * @param array an int array
12957      * @return the length of the array
12958      * @see java.lang.reflect.Array#getLength(java.lang.Object)
12959      * @since 1.0
12960      */
12961     public static int size(int[] array) {
12962         return Array.getLength(array);
12963     }
12964 
12965     /**
12966      * Allows arrays to behave similar to collections.
12967      * @param array a long array
12968      * @return the length of the array
12969      * @see java.lang.reflect.Array#getLength(java.lang.Object)
12970      * @since 1.0
12971      */
12972     public static int size(long[] array) {
12973         return Array.getLength(array);
12974     }
12975 
12976     /**
12977      * Allows arrays to behave similar to collections.
12978      * @param array a float array
12979      * @return the length of the array
12980      * @see java.lang.reflect.Array#getLength(java.lang.Object)
12981      * @since 1.0
12982      */
12983     public static int size(float[] array) {
12984         return Array.getLength(array);
12985     }
12986 
12987     /**
12988      * Allows arrays to behave similar to collections.
12989      * @param array a double array
12990      * @return the length of the array
12991      * @see java.lang.reflect.Array#getLength(java.lang.Object)
12992      * @since 1.0
12993      */
12994     public static int size(double[] array) {
12995         return Array.getLength(array);
12996     }
12997 
12998     /**
12999      * Converts this array to a List of the same size, with each element
13000      * added to the list.
13001      *
13002      * @param array a byte array
13003      * @return a list containing the contents of this array.
13004      * @since 1.0
13005      */
13006     @SuppressWarnings("unchecked")
13007     public static List<Byte> toList(byte[] array) {
13008         return DefaultTypeTransformation.primitiveArrayToList(array);
13009     }
13010 
13011     /**
13012      * Converts this array to a List of the same size, with each element
13013      * added to the list.
13014      *
13015      * @param array a boolean array
13016      * @return a list containing the contents of this array.
13017      * @since 1.6.0
13018      */
13019     @SuppressWarnings("unchecked")
13020     public static List<Boolean> toList(boolean[] array) {
13021         return DefaultTypeTransformation.primitiveArrayToList(array);
13022     }
13023 
13024     /**
13025      * Converts this array to a List of the same size, with each element
13026      * added to the list.
13027      *
13028      * @param array a char array
13029      * @return a list containing the contents of this array.
13030      * @since 1.0
13031      */
13032     @SuppressWarnings("unchecked")
13033     public static List<Character> toList(char[] array) {
13034         return DefaultTypeTransformation.primitiveArrayToList(array);
13035     }
13036 
13037     /**
13038      * Converts this array to a List of the same size, with each element
13039      * added to the list.
13040      *
13041      * @param array a short array
13042      * @return a list containing the contents of this array.
13043      * @since 1.0
13044      */
13045     @SuppressWarnings("unchecked")
13046     public static List<Short> toList(short[] array) {
13047         return DefaultTypeTransformation.primitiveArrayToList(array);
13048     }
13049 
13050     /**
13051      * Converts this array to a List of the same size, with each element
13052      * added to the list.
13053      *
13054      * @param array an int array
13055      * @return a list containing the contents of this array.
13056      * @since 1.0
13057      */
13058     @SuppressWarnings("unchecked")
13059     public static List<Integer> toList(int[] array) {
13060         return DefaultTypeTransformation.primitiveArrayToList(array);
13061     }
13062 
13063     /**
13064      * Converts this array to a List of the same size, with each element
13065      * added to the list.
13066      *
13067      * @param array a long array
13068      * @return a list containing the contents of this array.
13069      * @since 1.0
13070      */
13071     @SuppressWarnings("unchecked")
13072     public static List<Long> toList(long[] array) {
13073         return DefaultTypeTransformation.primitiveArrayToList(array);
13074     }
13075 
13076     /**
13077      * Converts this array to a List of the same size, with each element
13078      * added to the list.
13079      *
13080      * @param array a float array
13081      * @return a list containing the contents of this array.
13082      * @since 1.0
13083      */
13084     @SuppressWarnings("unchecked")
13085     public static List<Float> toList(float[] array) {
13086         return DefaultTypeTransformation.primitiveArrayToList(array);
13087     }
13088 
13089     /**
13090      * Converts this array to a List of the same size, with each element
13091      * added to the list.
13092      *
13093      * @param array a double array
13094      * @return a list containing the contents of this array.
13095      * @since 1.0
13096      */
13097     @SuppressWarnings("unchecked")
13098     public static List<Double> toList(double[] array) {
13099         return DefaultTypeTransformation.primitiveArrayToList(array);
13100     }
13101 
13102     /**
13103      * Converts this array to a Set, with each unique element
13104      * added to the set.
13105      *
13106      * @param array a byte array
13107      * @return a set containing the unique contents of this array.
13108      * @since 1.8.0
13109      */
13110     @SuppressWarnings("unchecked")
13111     public static Set<Byte> toSet(byte[] array) {
13112         return toSet(DefaultTypeTransformation.primitiveArrayToList(array));
13113     }
13114 
13115     /**
13116      * Converts this array to a Set, with each unique element
13117      * added to the set.
13118      *
13119      * @param array a boolean array
13120      * @return a set containing the unique contents of this array.
13121      * @since 1.8.0
13122      */
13123     @SuppressWarnings("unchecked")
13124     public static Set<Boolean> toSet(boolean[] array) {
13125         return toSet(DefaultTypeTransformation.primitiveArrayToList(array));
13126     }
13127 
13128     /**
13129      * Converts this array to a Set, with each unique element
13130      * added to the set.
13131      *
13132      * @param array a char array
13133      * @return a set containing the unique contents of this array.
13134      * @since 1.8.0
13135      */
13136     @SuppressWarnings("unchecked")
13137     public static Set<Character> toSet(char[] array) {
13138         return toSet(DefaultTypeTransformation.primitiveArrayToList(array));
13139     }
13140 
13141     /**
13142      * Converts this array to a Set, with each unique element
13143      * added to the set.
13144      *
13145      * @param array a short array
13146      * @return a set containing the unique contents of this array.
13147      * @since 1.8.0
13148      */
13149     @SuppressWarnings("unchecked")
13150     public static Set<Short> toSet(short[] array) {
13151         return toSet(DefaultTypeTransformation.primitiveArrayToList(array));
13152     }
13153 
13154     /**
13155      * Converts this array to a Set, with each unique element
13156      * added to the set.
13157      *
13158      * @param array an int array
13159      * @return a set containing the unique contents of this array.
13160      * @since 1.8.0
13161      */
13162     @SuppressWarnings("unchecked")
13163     public static Set<Integer> toSet(int[] array) {
13164         return toSet(DefaultTypeTransformation.primitiveArrayToList(array));
13165     }
13166 
13167     /**
13168      * Converts this array to a Set, with each unique element
13169      * added to the set.
13170      *
13171      * @param array a long array
13172      * @return a set containing the unique contents of this array.
13173      * @since 1.8.0
13174      */
13175     @SuppressWarnings("unchecked")
13176     public static Set<Long> toSet(long[] array) {
13177         return toSet(DefaultTypeTransformation.primitiveArrayToList(array));
13178     }
13179 
13180     /**
13181      * Converts this array to a Set, with each unique element
13182      * added to the set.
13183      *
13184      * @param array a float array
13185      * @return a set containing the unique contents of this array.
13186      * @since 1.8.0
13187      */
13188     @SuppressWarnings("unchecked")
13189     public static Set<Float> toSet(float[] array) {
13190         return toSet(DefaultTypeTransformation.primitiveArrayToList(array));
13191     }
13192 
13193     /**
13194      * Converts this array to a Set, with each unique element
13195      * added to the set.
13196      *
13197      * @param array a double array
13198      * @return a set containing the unique contents of this array.
13199      * @since 1.8.0
13200      */
13201     @SuppressWarnings("unchecked")
13202     public static Set<Double> toSet(double[] array) {
13203         return toSet(DefaultTypeTransformation.primitiveArrayToList(array));
13204     }
13205 
13206     /**
13207      * Convert a Collection to a Set. Always returns a new Set
13208      * even if the Collection is already a Set.
13209      * <p>
13210      * Example usage:
13211      * <pre class="groovyTestCase">
13212      * def result = [1, 2, 2, 2, 3].toSet()
13213      * assert result instanceof Set
13214      * assert result == [1, 2, 3] as Set
13215      * </pre>
13216      *
13217      * @param self a collection
13218      * @return a Set
13219      * @since 1.8.0
13220      */
13221     public static <T> Set<T> toSet(Collection<T> self) {
13222         Set<T> answer = new HashSet<T>(self.size());
13223         answer.addAll(self);
13224         return answer;
13225     }
13226 
13227     /**
13228      * Convert an Iterable to a Set. Always returns a new Set
13229      * even if the Iterable is already a Set.
13230      * <p>
13231      * Example usage:
13232      * <pre class="groovyTestCase">
13233      * def result = [1, 2, 2, 2, 3].toSet()
13234      * assert result instanceof Set
13235      * assert result == [1, 2, 3] as Set
13236      * </pre>
13237      *
13238      * @param self an Iterable
13239      * @return a Set
13240      * @since 2.4.0
13241      */
13242     public static <T> Set<T> toSet(Iterable<T> self) {
13243         return toSet(self.iterator());
13244     }
13245 
13246     /**
13247      * Convert an iterator to a Set. The iterator will become
13248      * exhausted of elements after making this conversion.
13249      *
13250      * @param self an iterator
13251      * @return a Set
13252      * @since 1.8.0
13253      */
13254     public static <T> Set<T> toSet(Iterator<T> self) {
13255         Set<T> answer = new HashSet<T>();
13256         while (self.hasNext()) {
13257             answer.add(self.next());
13258         }
13259         return answer;
13260     }
13261 
13262     /**
13263      * Convert an enumeration to a Set.
13264      *
13265      * @param self an enumeration
13266      * @return a Set
13267      * @since 1.8.0
13268      */
13269     public static <T> Set<T> toSet(Enumeration<T> self) {
13270         Set<T> answer = new HashSet<T>();
13271         while (self.hasMoreElements()) {
13272             answer.add(self.nextElement());
13273         }
13274         return answer;
13275     }
13276 
13277     /**
13278      * Implements the getAt(int) method for primitive type arrays.
13279      *
13280      * @param self an array object
13281      * @param idx  the index of interest
13282      * @return the returned value from the array
13283      * @since 1.5.0
13284      */
13285     protected static Object primitiveArrayGet(Object self, int idx) {
13286         return Array.get(self, normaliseIndex(idx, Array.getLength(self)));
13287     }
13288 
13289     /**
13290      * Implements the getAt(Range) method for primitive type arrays.
13291      *
13292      * @param self  an array object
13293      * @param range the range of indices of interest
13294      * @return the returned values from the array corresponding to the range
13295      * @since 1.5.0
13296      */
13297     protected static List primitiveArrayGet(Object self, Range range) {
13298         List answer = new ArrayList();
13299         for (Object next : range) {
13300             int idx = DefaultTypeTransformation.intUnbox(next);
13301             answer.add(primitiveArrayGet(self, idx));
13302         }
13303         return answer;
13304     }
13305 
13306     /**
13307      * Implements the getAt(Collection) method for primitive type arrays.  Each
13308      * value in the collection argument is assumed to be a valid array index.
13309      * The value at each index is then added to a list which is returned.
13310      *
13311      * @param self    an array object
13312      * @param indices the indices of interest
13313      * @return the returned values from the array
13314      * @since 1.0
13315      */
13316     protected static List primitiveArrayGet(Object self, Collection indices) {
13317         List answer = new ArrayList();
13318         for (Object value : indices) {
13319             if (value instanceof Range) {
13320                 answer.addAll(primitiveArrayGet(self, (Range) value));
13321             } else if (value instanceof List) {
13322                 answer.addAll(primitiveArrayGet(self, (List) value));
13323             } else {
13324                 int idx = DefaultTypeTransformation.intUnbox(value);
13325                 answer.add(primitiveArrayGet(self, idx));
13326             }
13327         }
13328         return answer;
13329     }
13330 
13331     /**
13332      * Implements the setAt(int idx) method for primitive type arrays.
13333      *
13334      * @param self     an object
13335      * @param idx      the index of interest
13336      * @param newValue the new value to be put into the index of interest
13337      * @return the added value
13338      * @since 1.5.0
13339      */
13340     protected static Object primitiveArrayPut(Object self, int idx, Object newValue) {
13341         Array.set(self, normaliseIndex(idx, Array.getLength(self)), newValue);
13342         return newValue;
13343     }
13344 
13345     /**
13346      * Identity conversion which returns Boolean.TRUE for a true Boolean and Boolean.FALSE for a false Boolean.
13347      *
13348      * @param self a Boolean
13349      * @return the original Boolean
13350      * @since 1.7.6
13351      */
13352     public static Boolean toBoolean(Boolean self) {
13353         return self;
13354     }
13355 
13356     /**
13357      * Checks whether the array contains the given value.
13358      *
13359      * @param self  the array we are searching
13360      * @param value the value being searched for
13361      * @return true if the array contains the value
13362      * @since 1.8.6
13363      */
13364     public static boolean contains(int[] self, Object value) {
13365         for (int next : self) {
13366             if (DefaultTypeTransformation.compareEqual(value, next)) return true;
13367         }
13368         return false;
13369     }
13370 
13371     /**
13372      * Checks whether the array contains the given value.
13373      *
13374      * @param self  the array we are searching
13375      * @param value the value being searched for
13376      * @return true if the array contains the value
13377      * @since 1.8.6
13378      */
13379     public static boolean contains(long[] self, Object value) {
13380         for (long next : self) {
13381             if (DefaultTypeTransformation.compareEqual(value, next)) return true;
13382         }
13383         return false;
13384     }
13385 
13386     /**
13387      * Checks whether the array contains the given value.
13388      *
13389      * @param self  the array we are searching
13390      * @param value the value being searched for
13391      * @return true if the array contains the value
13392      * @since 1.8.6
13393      */
13394     public static boolean contains(short[] self, Object value) {
13395         for (short next : self) {
13396             if (DefaultTypeTransformation.compareEqual(value, next)) return true;
13397         }
13398         return false;
13399     }
13400 
13401     /**
13402      * Checks whether the array contains the given value.
13403      *
13404      * @param self  the array we are searching
13405      * @param value the value being searched for
13406      * @return true if the array contains the value
13407      * @since 1.8.6
13408      */
13409     public static boolean contains(char[] self, Object value) {
13410         for (char next : self) {
13411             if (DefaultTypeTransformation.compareEqual(value, next)) return true;
13412         }
13413         return false;
13414     }
13415 
13416     /**
13417      * Checks whether the array contains the given value.
13418      *
13419      * @param self  the array within which we count the number of occurrences
13420      * @param value the value being searched for
13421      * @return the number of occurrences
13422      * @since 1.8.6
13423      */
13424     public static boolean contains(boolean[] self, Object value) {
13425         for (boolean next : self) {
13426             if (DefaultTypeTransformation.compareEqual(value, next)) return true;
13427         }
13428         return false;
13429     }
13430 
13431     /**
13432      * Checks whether the array contains the given value.
13433      *
13434      * @param self  the array we are searching
13435      * @param value the value being searched for
13436      * @return true if the array contains the value
13437      * @since 1.8.6
13438      */
13439     public static boolean contains(double[] self, Object value) {
13440         for (double next : self) {
13441             if (DefaultTypeTransformation.compareEqual(value, next)) return true;
13442         }
13443         return false;
13444     }
13445 
13446     /**
13447      * Checks whether the array contains the given value.
13448      *
13449      * @param self  the array we are searching
13450      * @param value the value being searched for
13451      * @return true if the array contains the value
13452      * @since 1.8.6
13453      */
13454     public static boolean contains(float[] self, Object value) {
13455         for (float next : self) {
13456             if (DefaultTypeTransformation.compareEqual(value, next)) return true;
13457         }
13458         return false;
13459     }
13460 
13461     /**
13462      * Checks whether the array contains the given value.
13463      *
13464      * @param self  the array we are searching
13465      * @param value the value being searched for
13466      * @return true if the array contains the value
13467      * @since 1.8.6
13468      */
13469     public static boolean contains(byte[] self, Object value) {
13470         for (byte next : self) {
13471             if (DefaultTypeTransformation.compareEqual(value, next)) return true;
13472         }
13473         return false;
13474     }
13475 
13476     /**
13477      * Checks whether the array contains the given value.
13478      *
13479      * @param self  the array we are searching
13480      * @param value the value being searched for
13481      * @return true if the array contains the value
13482      * @since 1.8.6
13483      */
13484     public static boolean contains(Object[] self, Object value) {
13485         for (Object next : self) {
13486             if (DefaultTypeTransformation.compareEqual(value, next)) return true;
13487         }
13488         return false;
13489     }
13490 
13491     /**
13492      * Returns the string representation of the given array.
13493      *
13494      * @param self an array
13495      * @return the string representation
13496      * @since 1.6.0
13497      */
13498     public static String toString(boolean[] self) {
13499         return InvokerHelper.toString(self);
13500     }
13501 
13502     /**
13503      * Returns the string representation of the given array.
13504      *
13505      * @param self an array
13506      * @return the string representation
13507      * @since 1.6.0
13508      */
13509     public static String toString(byte[] self) {
13510         return InvokerHelper.toString(self);
13511     }
13512 
13513     /**
13514      * Returns the string representation of the given array.
13515      *
13516      * @param self an array
13517      * @return the string representation
13518      * @since 1.6.0
13519      */
13520     public static String toString(char[] self) {
13521         return InvokerHelper.toString(self);
13522     }
13523 
13524     /**
13525      * Returns the string representation of the given array.
13526      *
13527      * @param self an array
13528      * @return the string representation
13529      * @since 1.6.0
13530      */
13531     public static String toString(short[] self) {
13532         return InvokerHelper.toString(self);
13533     }
13534 
13535     /**
13536      * Returns the string representation of the given array.
13537      *
13538      * @param self an array
13539      * @return the string representation
13540      * @since 1.6.0
13541      */
13542     public static String toString(int[] self) {
13543         return InvokerHelper.toString(self);
13544     }
13545 
13546     /**
13547      * Returns the string representation of the given array.
13548      *
13549      * @param self an array
13550      * @return the string representation
13551      * @since 1.6.0
13552      */
13553     public static String toString(long[] self) {
13554         return InvokerHelper.toString(self);
13555     }
13556 
13557     /**
13558      * Returns the string representation of the given array.
13559      *
13560      * @param self an array
13561      * @return the string representation
13562      * @since 1.6.0
13563      */
13564     public static String toString(float[] self) {
13565         return InvokerHelper.toString(self);
13566     }
13567 
13568     /**
13569      * Returns the string representation of the given array.
13570      *
13571      * @param self an array
13572      * @return the string representation
13573      * @since 1.6.0
13574      */
13575     public static String toString(double[] self) {
13576         return InvokerHelper.toString(self);
13577     }
13578 
13579     /**
13580      * Returns the string representation of the given map.
13581      *
13582      * @param self a Map
13583      * @return the string representation
13584      * @see #toMapString(java.util.Map)
13585      * @since 1.0
13586      */
13587     public static String toString(AbstractMap self) {
13588         return toMapString(self);
13589     }
13590 
13591     /**
13592      * Returns the string representation of this map.  The string displays the
13593      * contents of the map, i.e. <code>[one:1, two:2, three:3]</code>.
13594      *
13595      * @param self a Map
13596      * @return the string representation
13597      * @since 1.0
13598      */
13599     public static String toMapString(Map self) {
13600         return toMapString(self, -1);
13601     }
13602 
13603     /**
13604      * Returns the string representation of this map.  The string displays the
13605      * contents of the map, i.e. <code>[one:1, two:2, three:3]</code>.
13606      *
13607      * @param self a Map
13608      * @param maxSize stop after approximately this many characters and append '...'
13609      * @return the string representation
13610      * @since 1.0
13611      */
13612     public static String toMapString(Map self, int maxSize) {
13613         return (self == null) ? "null" : InvokerHelper.toMapString(self, maxSize);
13614     }
13615 
13616     /**
13617      * Returns the string representation of the given collection.  The string
13618      * displays the contents of the collection, i.e.
13619      * <code>[1, 2, a]</code>.
13620      *
13621      * @param self a Collection
13622      * @return the string representation
13623      * @see #toListString(java.util.Collection)
13624      * @since 1.0
13625      */
13626     public static String toString(AbstractCollection self) {
13627         return toListString(self);
13628     }
13629 
13630     /**
13631      * Returns the string representation of the given list.  The string
13632      * displays the contents of the list, similar to a list literal, i.e.
13633      * <code>[1, 2, a]</code>.
13634      *
13635      * @param self a Collection
13636      * @return the string representation
13637      * @since 1.0
13638      */
13639     public static String toListString(Collection self) {
13640         return toListString(self, -1);
13641     }
13642 
13643     /**
13644      * Returns the string representation of the given list.  The string
13645      * displays the contents of the list, similar to a list literal, i.e.
13646      * <code>[1, 2, a]</code>.
13647      *
13648      * @param self a Collection
13649      * @param maxSize stop after approximately this many characters and append '...'
13650      * @return the string representation
13651      * @since 1.7.3
13652      */
13653     public static String toListString(Collection self, int maxSize) {
13654         return (self == null) ? "null" : InvokerHelper.toListString(self, maxSize);
13655     }
13656 
13657     /**
13658      * Returns the string representation of this array's contents.
13659      *
13660      * @param self an Object[]
13661      * @return the string representation
13662      * @see #toArrayString(java.lang.Object[])
13663      * @since 1.0
13664      */
13665     public static String toString(Object[] self) {
13666         return toArrayString(self);
13667     }
13668 
13669     /**
13670      * Returns the string representation of the given array.  The string
13671      * displays the contents of the array, similar to an array literal, i.e.
13672      * <code>{1, 2, "a"}</code>.
13673      *
13674      * @param self an Object[]
13675      * @return the string representation
13676      * @since 1.0
13677      */
13678     public static String toArrayString(Object[] self) {
13679         return (self == null) ? "null" : InvokerHelper.toArrayString(self);
13680     }
13681 
13682     /**
13683      * Create a String representation of this object.
13684      * @param value an object
13685      * @return a string.
13686      * @since 1.0
13687      */
13688     public static String toString(Object value) {
13689         return InvokerHelper.toString(value);
13690     }
13691 
13692     // Number based methods
13693     //-------------------------------------------------------------------------
13694 
13695     /**
13696      * Increment a Character by one.
13697      *
13698      * @param self a Character
13699      * @return an incremented Character
13700      * @since 1.5.7
13701      */
13702     public static Character next(Character self) {
13703         return (char) (self + 1);
13704     }
13705 
13706     /**
13707      * Increment a Number by one.
13708      *
13709      * @param self a Number
13710      * @return an incremented Number
13711      * @since 1.0
13712      */
13713     public static Number next(Number self) {
13714         return NumberNumberPlus.plus(self, ONE);
13715     }
13716 
13717     /**
13718      * Decrement a Character by one.
13719      *
13720      * @param self a Character
13721      * @return a decremented Character
13722      * @since 1.5.7
13723      */
13724     public static Character previous(Character self) {
13725         return (char) (self - 1);
13726     }
13727 
13728     /**
13729      * Decrement a Number by one.
13730      *
13731      * @param self a Number
13732      * @return a decremented Number
13733      * @since 1.0
13734      */
13735     public static Number previous(Number self) {
13736         return NumberNumberMinus.minus(self, ONE);
13737     }
13738 
13739     /**
13740      * Add a Character and a Number. The ordinal value of the Character
13741      * is used in the addition (the ordinal value is the unicode
13742      * value which for simple character sets is the ASCII value).
13743      * This operation will always create a new object for the result,
13744      * while the operands remain unchanged.
13745      *
13746      * @see java.lang.Integer#valueOf(int)
13747      * @param left  a Character
13748      * @param right a Number
13749      * @return the Number corresponding to the addition of left and right
13750      * @since 1.0
13751      */
13752     public static Number plus(Character left, Number right) {
13753         return NumberNumberPlus.plus(Integer.valueOf(left), right);
13754     }
13755 
13756     /**
13757      * Add a Number and a Character.  The ordinal value of the Character
13758      * is used in the addition (the ordinal value is the unicode
13759      * value which for simple character sets is the ASCII value).
13760      *
13761      * @see java.lang.Integer#valueOf(int)
13762      * @param left  a Number
13763      * @param right a Character
13764      * @return The Number corresponding to the addition of left and right
13765      * @since 1.0
13766      */
13767     public static Number plus(Number left, Character right) {
13768         return NumberNumberPlus.plus(left, Integer.valueOf(right));
13769     }
13770 
13771     /**
13772      * Add one Character to another. The ordinal values of the Characters
13773      * are used in the addition (the ordinal value is the unicode
13774      * value which for simple character sets is the ASCII value).
13775      * This operation will always create a new object for the result,
13776      * while the operands remain unchanged.
13777      *
13778      * @see #plus(java.lang.Number, java.lang.Character)
13779      * @param left  a Character
13780      * @param right a Character
13781      * @return the Number corresponding to the addition of left and right
13782      * @since 1.0
13783      */
13784     public static Number plus(Character left, Character right) {
13785         return plus(Integer.valueOf(left), right);
13786     }
13787 
13788     /**
13789      * Compare a Character and a Number. The ordinal value of the Character
13790      * is used in the comparison (the ordinal value is the unicode
13791      * value which for simple character sets is the ASCII value).
13792      *
13793      * @param left  a Character
13794      * @param right a Number
13795      * @return the result of the comparison
13796      * @since 1.0
13797      */
13798     public static int compareTo(Character left, Number right) {
13799         return compareTo(Integer.valueOf(left), right);
13800     }
13801 
13802     /**
13803      * Compare a Number and a Character. The ordinal value of the Character
13804      * is used in the comparison (the ordinal value is the unicode
13805      * value which for simple character sets is the ASCII value).
13806      *
13807      * @param left  a Number
13808      * @param right a Character
13809      * @return the result of the comparison
13810      * @since 1.0
13811      */
13812     public static int compareTo(Number left, Character right) {
13813         return compareTo(left, Integer.valueOf(right));
13814     }
13815 
13816     /**
13817      * Compare two Characters. The ordinal values of the Characters
13818      * are compared (the ordinal value is the unicode
13819      * value which for simple character sets is the ASCII value).
13820      *
13821      * @param left  a Character
13822      * @param right a Character
13823      * @return the result of the comparison
13824      * @since 1.0
13825      */
13826     public static int compareTo(Character left, Character right) {
13827         return compareTo(Integer.valueOf(left), right);
13828     }
13829 
13830     /**
13831      * Compare two Numbers.  Equality (==) for numbers dispatches to this.
13832      *
13833      * @param left  a Number
13834      * @param right another Number to compare to
13835      * @return the comparison of both numbers
13836      * @since 1.0
13837      */
13838     public static int compareTo(Number left, Number right) {
13839         /** @todo maybe a double dispatch thing to handle new large numbers? */
13840         return NumberMath.compareTo(left, right);
13841     }
13842 
13843     /**
13844      * Subtract a Number from a Character. The ordinal value of the Character
13845      * is used in the subtraction (the ordinal value is the unicode
13846      * value which for simple character sets is the ASCII value).
13847      *
13848      * @param left  a Character
13849      * @param right a Number
13850      * @return the Number corresponding to the subtraction of right from left
13851      * @since 1.0
13852      */
13853     public static Number minus(Character left, Number right) {
13854         return NumberNumberMinus.minus(Integer.valueOf(left), right);
13855     }
13856 
13857     /**
13858      * Subtract a Character from a Number. The ordinal value of the Character
13859      * is used in the subtraction (the ordinal value is the unicode
13860      * value which for simple character sets is the ASCII value).
13861      *
13862      * @param left  a Number
13863      * @param right a Character
13864      * @return the Number corresponding to the subtraction of right from left
13865      * @since 1.0
13866      */
13867     public static Number minus(Number left, Character right) {
13868         return NumberNumberMinus.minus(left, Integer.valueOf(right));
13869     }
13870 
13871     /**
13872      * Subtract one Character from another. The ordinal values of the Characters
13873      * is used in the comparison (the ordinal value is the unicode
13874      * value which for simple character sets is the ASCII value).
13875      *
13876      * @param left  a Character
13877      * @param right a Character
13878      * @return the Number corresponding to the subtraction of right from left
13879      * @since 1.0
13880      */
13881     public static Number minus(Character left, Character right) {
13882         return minus(Integer.valueOf(left), right);
13883     }
13884 
13885     /**
13886      * Multiply a Character by a Number. The ordinal value of the Character
13887      * is used in the multiplication (the ordinal value is the unicode
13888      * value which for simple character sets is the ASCII value).
13889      *
13890      * @param left  a Character
13891      * @param right a Number
13892      * @return the Number corresponding to the multiplication of left by right
13893      * @since 1.0
13894      */
13895     public static Number multiply(Character left, Number right) {
13896         return NumberNumberMultiply.multiply(Integer.valueOf(left), right);
13897     }
13898 
13899     /**
13900      * Multiply a Number by a Character. The ordinal value of the Character
13901      * is used in the multiplication (the ordinal value is the unicode
13902      * value which for simple character sets is the ASCII value).
13903      *
13904      * @param left  a Number
13905      * @param right a Character
13906      * @return the multiplication of left by right
13907      * @since 1.0
13908      */
13909     public static Number multiply(Number left, Character right) {
13910         return NumberNumberMultiply.multiply(Integer.valueOf(right), left);
13911     }
13912 
13913     /**
13914      * Multiply two Characters. The ordinal values of the Characters
13915      * are used in the multiplication (the ordinal value is the unicode
13916      * value which for simple character sets is the ASCII value).
13917      *
13918      * @param left  a Character
13919      * @param right another Character
13920      * @return the Number corresponding to the multiplication of left by right
13921      * @since 1.0
13922      */
13923     public static Number multiply(Character left, Character right) {
13924         return multiply(Integer.valueOf(left), right);
13925     }
13926 
13927     /**
13928      * Multiply a BigDecimal and a Double.
13929      * Note: This method was added to enforce the Groovy rule of
13930      * BigDecimal*Double == Double. Without this method, the
13931      * multiply(BigDecimal) method in BigDecimal would respond
13932      * and return a BigDecimal instead. Since BigDecimal is preferred
13933      * over Number, the Number*Number method is not chosen as in older
13934      * versions of Groovy.
13935      *
13936      * @param left  a BigDecimal
13937      * @param right a Double
13938      * @return the multiplication of left by right
13939      * @since 1.0
13940      */
13941     public static Number multiply(BigDecimal left, Double right) {
13942         return NumberMath.multiply(left, right);
13943     }
13944 
13945     /**
13946      * Multiply a BigDecimal and a BigInteger.
13947      * Note: This method was added to enforce the Groovy rule of
13948      * BigDecimal*long == long. Without this method, the
13949      * multiply(BigDecimal) method in BigDecimal would respond
13950      * and return a BigDecimal instead. Since BigDecimal is preferred
13951      * over Number, the Number*Number method is not chosen as in older
13952      * versions of Groovy. BigInteger is the fallback for all integer
13953      * types in Groovy
13954      *
13955      * @param left  a BigDecimal
13956      * @param right a BigInteger
13957      * @return the multiplication of left by right
13958      * @since 1.0
13959      */
13960     public static Number multiply(BigDecimal left, BigInteger right) {
13961         return NumberMath.multiply(left, right);
13962     }
13963 
13964     /**
13965      * Power of a Number to a certain exponent. Called by the '**' operator.
13966      *
13967      * @param self     a Number
13968      * @param exponent a Number exponent
13969      * @return a Number to the power of a certain exponent
13970      * @since 1.0
13971      */
13972     public static Number power(Number self, Number exponent) {
13973         double base, exp, answer;
13974         base = self.doubleValue();
13975         exp = exponent.doubleValue();
13976 
13977         answer = Math.pow(base, exp);
13978         if ((double) ((int) answer) == answer) {
13979             return (int) answer;
13980         } else if ((double) ((long) answer) == answer) {
13981             return (long) answer;
13982         } else {
13983             return answer;
13984         }
13985     }
13986 
13987     /**
13988      * Power of a BigDecimal to an integer certain exponent. If the
13989      * exponent is positive, call the BigDecimal.pow(int) method to
13990      * maintain precision. Called by the '**' operator.
13991      *
13992      * @param self     a BigDecimal
13993      * @param exponent an Integer exponent
13994      * @return a Number to the power of a the exponent
13995      */
13996     public static Number power(BigDecimal self, Integer exponent) {
13997         if (exponent >= 0) {
13998             return self.pow(exponent);
13999         } else {
14000             return power(self, (double) exponent);
14001         }
14002     }
14003 
14004     /**
14005      * Power of a BigInteger to an integer certain exponent. If the
14006      * exponent is positive, call the BigInteger.pow(int) method to
14007      * maintain precision. Called by the '**' operator.
14008      *
14009      *  @param self     a BigInteger
14010      *  @param exponent an Integer exponent
14011      *  @return a Number to the power of a the exponent
14012      */
14013     public static Number power(BigInteger self, Integer exponent) {
14014         if (exponent >= 0) {
14015             return self.pow(exponent);
14016         } else {
14017             return power(self, (double) exponent);
14018         }
14019     }
14020 
14021     /**
14022      * Power of an integer to an integer certain exponent. If the
14023      * exponent is positive, convert to a BigInteger and call
14024      * BigInteger.pow(int) method to maintain precision. Called by the
14025      * '**' operator.
14026      *
14027      *  @param self     an Integer
14028      *  @param exponent an Integer exponent
14029      *  @return a Number to the power of a the exponent
14030      */
14031     public static Number power(Integer self, Integer exponent) {
14032         if (exponent >= 0) {
14033             BigInteger answer = BigInteger.valueOf(self).pow(exponent);
14034             if (answer.compareTo(BI_INT_MIN) >= 0 && answer.compareTo(BI_INT_MAX) <= 0) {
14035                 return answer.intValue();
14036             } else {
14037                 return answer;
14038             }
14039         } else {
14040             return power(self, (double) exponent);
14041         }
14042     }
14043 
14044     /**
14045      * Power of a long to an integer certain exponent. If the
14046      * exponent is positive, convert to a BigInteger and call
14047      * BigInteger.pow(int) method to maintain precision. Called by the
14048      * '**' operator.
14049      *
14050      * @param self     a Long
14051      * @param exponent an Integer exponent
14052      * @return a Number to the power of a the exponent
14053      */
14054     public static Number power(Long self, Integer exponent) {
14055         if (exponent >= 0) {
14056             BigInteger answer = BigInteger.valueOf(self).pow(exponent);
14057             if (answer.compareTo(BI_LONG_MIN) >= 0 && answer.compareTo(BI_LONG_MAX) <= 0) {
14058                 return answer.longValue();
14059             } else {
14060                 return answer;
14061             }
14062         } else {
14063             return power(self, (double) exponent);
14064         }
14065     }
14066 
14067     /**
14068      * Power of a BigInteger to an BigInteger certain exponent. Called by the
14069      * '**' operator.
14070      *
14071      * @param self     a BigInteger
14072      * @param exponent an BigInteger exponent
14073      * @return a BigInteger to the power of a the exponent
14074      * @since 2.3.8
14075      */
14076     public static BigInteger power(BigInteger self, BigInteger exponent) {
14077         if ((exponent.signum() >= 0) && (exponent.compareTo(BI_INT_MAX) <= 0)) {
14078             return self.pow(exponent.intValue());
14079         } else {
14080             return BigDecimal.valueOf(Math.pow(self.doubleValue(), exponent.doubleValue())).toBigInteger();
14081         }
14082     }
14083 
14084     /**
14085      * Divide a Character by a Number. The ordinal value of the Character
14086      * is used in the division (the ordinal value is the unicode
14087      * value which for simple character sets is the ASCII value).
14088      *
14089      * @param left  a Character
14090      * @param right a Number
14091      * @return the Number corresponding to the division of left by right
14092      * @since 1.0
14093      */
14094     public static Number div(Character left, Number right) {
14095         return NumberNumberDiv.div(Integer.valueOf(left), right);
14096     }
14097 
14098     /**
14099      * Divide a Number by a Character. The ordinal value of the Character
14100      * is used in the division (the ordinal value is the unicode
14101      * value which for simple character sets is the ASCII value).
14102      *
14103      * @param left  a Number
14104      * @param right a Character
14105      * @return the Number corresponding to the division of left by right
14106      * @since 1.0
14107      */
14108     public static Number div(Number left, Character right) {
14109         return NumberNumberDiv.div(left, Integer.valueOf(right));
14110     }
14111 
14112     /**
14113      * Divide one Character by another. The ordinal values of the Characters
14114      * are used in the division (the ordinal value is the unicode
14115      * value which for simple character sets is the ASCII value).
14116      *
14117      * @param left  a Character
14118      * @param right another Character
14119      * @return the Number corresponding to the division of left by right
14120      * @since 1.0
14121      */
14122     public static Number div(Character left, Character right) {
14123         return div(Integer.valueOf(left), right);
14124     }
14125 
14126     /**
14127      * Integer Divide a Character by a Number. The ordinal value of the Character
14128      * is used in the division (the ordinal value is the unicode
14129      * value which for simple character sets is the ASCII value).
14130      *
14131      * @param left  a Character
14132      * @param right a Number
14133      * @return a Number (an Integer) resulting from the integer division operation
14134      * @since 1.0
14135      */
14136     public static Number intdiv(Character left, Number right) {
14137         return intdiv(Integer.valueOf(left), right);
14138     }
14139 
14140     /**
14141      * Integer Divide a Number by a Character. The ordinal value of the Character
14142      * is used in the division (the ordinal value is the unicode
14143      * value which for simple character sets is the ASCII value).
14144      *
14145      * @param left  a Number
14146      * @param right a Character
14147      * @return a Number (an Integer) resulting from the integer division operation
14148      * @since 1.0
14149      */
14150     public static Number intdiv(Number left, Character right) {
14151         return intdiv(left, Integer.valueOf(right));
14152     }
14153 
14154     /**
14155      * Integer Divide two Characters. The ordinal values of the Characters
14156      * are used in the division (the ordinal value is the unicode
14157      * value which for simple character sets is the ASCII value).
14158      *
14159      * @param left  a Character
14160      * @param right another Character
14161      * @return a Number (an Integer) resulting from the integer division operation
14162      * @since 1.0
14163      */
14164     public static Number intdiv(Character left, Character right) {
14165         return intdiv(Integer.valueOf(left), right);
14166     }
14167 
14168     /**
14169      * Integer Divide two Numbers.
14170      *
14171      * @param left  a Number
14172      * @param right another Number
14173      * @return a Number (an Integer) resulting from the integer division operation
14174      * @since 1.0
14175      */
14176     public static Number intdiv(Number left, Number right) {
14177         return NumberMath.intdiv(left, right);
14178     }
14179 
14180     /**
14181      * Bitwise OR together two numbers.
14182      *
14183      * @param left  a Number
14184      * @param right another Number to bitwise OR
14185      * @return the bitwise OR of both Numbers
14186      * @since 1.0
14187      */
14188     public static Number or(Number left, Number right) {
14189         return NumberMath.or(left, right);
14190     }
14191 
14192     /**
14193      * Bitwise AND together two Numbers.
14194      *
14195      * @param left  a Number
14196      * @param right another Number to bitwise AND
14197      * @return the bitwise AND of both Numbers
14198      * @since 1.0
14199      */
14200     public static Number and(Number left, Number right) {
14201         return NumberMath.and(left, right);
14202     }
14203 
14204     /**
14205      * Bitwise AND together two BitSets.
14206      *
14207      * @param left  a BitSet
14208      * @param right another BitSet to bitwise AND
14209      * @return the bitwise AND of both BitSets
14210      * @since 1.5.0
14211      */
14212     public static BitSet and(BitSet left, BitSet right) {
14213         BitSet result = (BitSet) left.clone();
14214         result.and(right);
14215         return result;
14216     }
14217 
14218     /**
14219      * Bitwise XOR together two BitSets.  Called when the '^' operator is used
14220      * between two bit sets.
14221      *
14222      * @param left  a BitSet
14223      * @param right another BitSet to bitwise AND
14224      * @return the bitwise XOR of both BitSets
14225      * @since 1.5.0
14226      */
14227     public static BitSet xor(BitSet left, BitSet right) {
14228         BitSet result = (BitSet) left.clone();
14229         result.xor(right);
14230         return result;
14231     }
14232 
14233     /**
14234      * Bitwise NEGATE a BitSet.
14235      *
14236      * @param self a BitSet
14237      * @return the bitwise NEGATE of the BitSet
14238      * @since 1.5.0
14239      */
14240     public static BitSet bitwiseNegate(BitSet self) {
14241         BitSet result = (BitSet) self.clone();
14242         result.flip(0, result.size() - 1);
14243         return result;
14244     }
14245 
14246     /**
14247      * Bitwise NEGATE a Number.
14248      *
14249      * @param left a Number
14250      * @return the bitwise NEGATE of the Number
14251      * @since 2.2.0
14252      */
14253     public static Number bitwiseNegate(Number left) {
14254         return NumberMath.bitwiseNegate(left);
14255     }
14256 
14257     /**
14258      * Bitwise OR together two BitSets.  Called when the '|' operator is used
14259      * between two bit sets.
14260      *
14261      * @param left  a BitSet
14262      * @param right another BitSet to bitwise AND
14263      * @return the bitwise OR of both BitSets
14264      * @since 1.5.0
14265      */
14266     public static BitSet or(BitSet left, BitSet right) {
14267         BitSet result = (BitSet) left.clone();
14268         result.or(right);
14269         return result;
14270     }
14271 
14272     /**
14273      * Bitwise XOR together two Numbers.  Called when the '^' operator is used.
14274      *
14275      * @param left  a Number
14276      * @param right another Number to bitwse XOR
14277      * @return the bitwise XOR of both Numbers
14278      * @since 1.0
14279      */
14280     public static Number xor(Number left, Number right) {
14281         return NumberMath.xor(left, right);
14282     }
14283 
14284     /**
14285      * Performs a division modulus operation.  Called by the '%' operator.
14286      *
14287      * @param left  a Number
14288      * @param right another Number to mod
14289      * @return the modulus result
14290      * @since 1.0
14291      */
14292     public static Number mod(Number left, Number right) {
14293         return NumberMath.mod(left, right);
14294     }
14295 
14296     /**
14297      * Negates the number.  Equivalent to the '-' operator when it preceeds
14298      * a single operand, i.e. <code>-10</code>
14299      *
14300      * @param left a Number
14301      * @return the negation of the number
14302      * @since 1.5.0
14303      */
14304     public static Number unaryMinus(Number left) {
14305         return NumberMath.unaryMinus(left);
14306     }
14307 
14308     /**
14309      * Returns the number, effectively being a noop for numbers.
14310      * Operator overloaded form of the '+' operator when it preceeds
14311      * a single operand, i.e. <code>+10</code>
14312      *
14313      * @param left a Number
14314      * @return the number
14315      * @since 2.2.0
14316      */
14317     public static Number unaryPlus(Number left) {
14318         return NumberMath.unaryPlus(left);
14319     }
14320 
14321     /**
14322      * Executes the closure this many times, starting from zero.  The current
14323      * index is passed to the closure each time.
14324      * Example:
14325      * <pre>10.times {
14326      *   println it
14327      * }</pre>
14328      * Prints the numbers 0 through 9.
14329      *
14330      * @param self    a Number
14331      * @param closure the closure to call a number of times
14332      * @since 1.0
14333      */
14334     public static void times(Number self, @ClosureParams(value=SimpleType.class,options="int")  Closure closure) {
14335         for (int i = 0, size = self.intValue(); i < size; i++) {
14336             closure.call(i);
14337             if (closure.getDirective() == Closure.DONE) {
14338                 break;
14339             }
14340         }
14341     }
14342 
14343     /**
14344      * Iterates from this number up to the given number, inclusive,
14345      * incrementing by one each time.
14346      *
14347      * @param self    a Number
14348      * @param to      another Number to go up to
14349      * @param closure the closure to call
14350      * @since 1.0
14351      */
14352     public static void upto(Number self, Number to, @ClosureParams(FirstParam.class) Closure closure) {
14353         int self1 = self.intValue();
14354         int to1 = to.intValue();
14355         if (self1 <= to1) {
14356             for (int i = self1; i <= to1; i++) {
14357                 closure.call(i);
14358             }
14359         } else
14360             throw new GroovyRuntimeException("The argument (" + to + 
14361                     ") to upto() cannot be less than the value (" + self + ") it's called on.");
14362     }
14363 
14364     /**
14365      * Iterates from this number up to the given number, inclusive,
14366      * incrementing by one each time.
14367      *
14368      * @param self    a long
14369      * @param to the end number
14370      * @param closure the code to execute for each number
14371      * @since 1.0
14372      */
14373     public static void upto(long self, Number to, @ClosureParams(FirstParam.class) Closure closure) {
14374         long to1 = to.longValue();
14375         if (self <= to1) {
14376             for (long i = self; i <= to1; i++) {
14377                 closure.call(i);
14378             }
14379         } else
14380             throw new GroovyRuntimeException("The argument (" + to + 
14381                     ") to upto() cannot be less than the value (" + self + ") it's called on.");
14382     }
14383 
14384     /**
14385      * Iterates from this number up to the given number, inclusive,
14386      * incrementing by one each time.
14387      *
14388      * @param self    a Long
14389      * @param to the end number
14390      * @param closure the code to execute for each number
14391      * @since 1.0
14392      */
14393     public static void upto(Long self, Number to, @ClosureParams(FirstParam.class) Closure closure) {
14394         long to1 = to.longValue();
14395         if (self <= to1) {
14396             for (long i = self; i <= to1; i++) {
14397                 closure.call(i);
14398             }
14399         } else
14400             throw new GroovyRuntimeException("The argument (" + to + 
14401                     ") to upto() cannot be less than the value (" + self + ") it's called on.");
14402     }
14403 
14404     /**
14405      * Iterates from this number up to the given number, inclusive,
14406      * incrementing by one each time.
14407      *
14408      * @param self    a float
14409      * @param to the end number
14410      * @param closure the code to execute for each number
14411      * @since 1.0
14412      */
14413     public static void upto(float self, Number to, @ClosureParams(FirstParam.class) Closure closure) {
14414         float to1 = to.floatValue();
14415         if (self <= to1) {
14416             for (float i = self; i <= to1; i++) {
14417                 closure.call(i);
14418             }
14419         } else
14420             throw new GroovyRuntimeException("The argument (" + to + 
14421                     ") to upto() cannot be less than the value (" + self + ") it's called on.");
14422     }
14423 
14424     /**
14425      * Iterates from this number up to the given number, inclusive,
14426      * incrementing by one each time.
14427      *
14428      * @param self    a Float
14429      * @param to the end number
14430      * @param closure the code to execute for each number
14431      * @since 1.0
14432      */
14433     public static void upto(Float self, Number to, @ClosureParams(FirstParam.class) Closure closure) {
14434         float to1 = to.floatValue();
14435         if (self <= to1) {
14436             for (float i = self; i <= to1; i++) {
14437                 closure.call(i);
14438             }
14439         } else
14440             throw new GroovyRuntimeException("The argument (" + to + 
14441                     ") to upto() cannot be less than the value (" + self + ") it's called on.");
14442     }
14443 
14444     /**
14445      * Iterates from this number up to the given number, inclusive,
14446      * incrementing by one each time.
14447      *
14448      * @param self    a double
14449      * @param to the end number
14450      * @param closure the code to execute for each number
14451      * @since 1.0
14452      */
14453     public static void upto(double self, Number to, @ClosureParams(FirstParam.class) Closure closure) {
14454         double to1 = to.doubleValue();
14455         if (self <= to1) {
14456             for (double i = self; i <= to1; i++) {
14457                 closure.call(i);
14458             }
14459         } else
14460             throw new GroovyRuntimeException("The argument (" + to + 
14461                     ") to upto() cannot be less than the value (" + self + ") it's called on.");
14462     }
14463 
14464     /**
14465      * Iterates from this number up to the given number, inclusive,
14466      * incrementing by one each time.
14467      *
14468      * @param self    a Double
14469      * @param to the end number
14470      * @param closure the code to execute for each number
14471      * @since 1.0
14472      */
14473     public static void upto(Double self, Number to, @ClosureParams(FirstParam.class) Closure closure) {
14474         double to1 = to.doubleValue();
14475         if (self <= to1) {
14476             for (double i = self; i <= to1; i++) {
14477                 closure.call(i);
14478             }
14479         } else
14480             throw new GroovyRuntimeException("The argument (" + to + 
14481                     ") to upto() cannot be less than the value (" + self + ") it's called on.");
14482     }
14483 
14484     /**
14485      * Iterates from this number up to the given number, inclusive,
14486      * incrementing by one each time.  Example:
14487      * <pre>0.upto( 10 ) {
14488      *   println it
14489      * }</pre>
14490      * Prints numbers 0 to 10
14491      *
14492      * @param self    a BigInteger
14493      * @param to the end number
14494      * @param closure the code to execute for each number
14495      * @since 1.0
14496      */
14497     public static void upto(BigInteger self, Number to, @ClosureParams(FirstParam.class) Closure closure) {
14498         if (to instanceof BigDecimal) {
14499             final BigDecimal one = BigDecimal.valueOf(10, 1);
14500             BigDecimal self1 = new BigDecimal(self);
14501             BigDecimal to1 = (BigDecimal) to;
14502             if (self1.compareTo(to1) <= 0) {
14503                 for (BigDecimal i = self1; i.compareTo(to1) <= 0; i = i.add(one)) {
14504                     closure.call(i);
14505                 }
14506             } else
14507                 throw new GroovyRuntimeException(
14508                         MessageFormat.format(
14509                                 "The argument ({0}) to upto() cannot be less than the value ({1}) it''s called on.",
14510                                 to, self));
14511         } else if (to instanceof BigInteger) {
14512             final BigInteger one = BigInteger.valueOf(1);
14513             BigInteger to1 = (BigInteger) to;
14514             if (self.compareTo(to1) <= 0) {
14515                 for (BigInteger i = self; i.compareTo(to1) <= 0; i = i.add(one)) {
14516                     closure.call(i);
14517                 }
14518             } else
14519                 throw new GroovyRuntimeException(
14520                         MessageFormat.format("The argument ({0}) to upto() cannot be less than the value ({1}) it''s called on.",
14521                                 to, self));
14522         } else {
14523             final BigInteger one = BigInteger.valueOf(1);
14524             BigInteger to1 = new BigInteger(to.toString());
14525             if (self.compareTo(to1) <= 0) {
14526                 for (BigInteger i = self; i.compareTo(to1) <= 0; i = i.add(one)) {
14527                     closure.call(i);
14528                 }
14529             } else
14530                 throw new GroovyRuntimeException(MessageFormat.format(
14531                         "The argument ({0}) to upto() cannot be less than the value ({1}) it''s called on.",
14532                         to, self));
14533         }
14534     }
14535 
14536     /**
14537      * Iterates from this number up to the given number, inclusive,
14538      * incrementing by one each time.
14539      * <pre>0.1.upto( 10 ) {
14540      *   println it
14541      * }</pre>
14542      * Prints numbers 0.1, 1.1, 2.1... to 9.1
14543      *
14544      * @param self    a BigDecimal
14545      * @param to the end number
14546      * @param closure the code to execute for each number
14547      * @since 1.0
14548      */
14549     public static void upto(BigDecimal self, Number to, @ClosureParams(FirstParam.class) Closure closure) {
14550         final BigDecimal one = BigDecimal.valueOf(10, 1);  // That's what you get for "1.0".
14551         if (to instanceof BigDecimal) {
14552             BigDecimal to1 = (BigDecimal) to;
14553             if (self.compareTo(to1) <= 0) {
14554                 for (BigDecimal i = self; i.compareTo(to1) <= 0; i = i.add(one)) {
14555                     closure.call(i);
14556                 }
14557             } else
14558                 throw new GroovyRuntimeException("The argument (" + to + 
14559                         ") to upto() cannot be less than the value (" + self + ") it's called on.");
14560         } else if (to instanceof BigInteger) {
14561             BigDecimal to1 = new BigDecimal((BigInteger) to);
14562             if (self.compareTo(to1) <= 0) {
14563                 for (BigDecimal i = self; i.compareTo(to1) <= 0; i = i.add(one)) {
14564                     closure.call(i);
14565                 }
14566             } else
14567                 throw new GroovyRuntimeException("The argument (" + to + 
14568                         ") to upto() cannot be less than the value (" + self + ") it's called on.");
14569         } else {
14570             BigDecimal to1 = new BigDecimal(to.toString());
14571             if (self.compareTo(to1) <= 0) {
14572                 for (BigDecimal i = self; i.compareTo(to1) <= 0; i = i.add(one)) {
14573                     closure.call(i);
14574                 }
14575             } else
14576                 throw new GroovyRuntimeException("The argument (" + to + 
14577                         ") to upto() cannot be less than the value (" + self + ") it's called on.");
14578         }
14579     }
14580 
14581     /**
14582      * Iterates from this number down to the given number, inclusive,
14583      * decrementing by one each time.
14584      *
14585      * @param self    a Number
14586      * @param to      another Number to go down to
14587      * @param closure the closure to call
14588      * @since 1.0
14589      */
14590     public static void downto(Number self, Number to, @ClosureParams(FirstParam.class) Closure closure) {
14591         int self1 = self.intValue();
14592         int to1 = to.intValue();
14593         if (self1 >= to1) {
14594             for (int i = self1; i >= to1; i--) {
14595                 closure.call(i);
14596             }
14597         } else
14598             throw new GroovyRuntimeException("The argument (" + to + 
14599                     ") to downto() cannot be greater than the value (" + self + ") it's called on.");
14600     }
14601 
14602     /**
14603      * Iterates from this number down to the given number, inclusive,
14604      * decrementing by one each time.
14605      *
14606      * @param self    a long
14607      * @param to the end number
14608      * @param closure the code to execute for each number
14609      * @since 1.0
14610      */
14611     public static void downto(long self, Number to, @ClosureParams(FirstParam.class) Closure closure) {
14612         long to1 = to.longValue();
14613         if (self >= to1) {
14614             for (long i = self; i >= to1; i--) {
14615                 closure.call(i);
14616             }
14617         } else
14618             throw new GroovyRuntimeException("The argument (" + to + 
14619                     ") to downto() cannot be greater than the value (" + self + ") it's called on.");
14620     }
14621 
14622     /**
14623      * Iterates from this number down to the given number, inclusive,
14624      * decrementing by one each time.
14625      *
14626      * @param self    a Long
14627      * @param to the end number
14628      * @param closure the code to execute for each number
14629      * @since 1.0
14630      */
14631     public static void downto(Long self, Number to, @ClosureParams(FirstParam.class) Closure closure) {
14632         long to1 = to.longValue();
14633         if (self >= to1) {
14634             for (long i = self; i >= to1; i--) {
14635                 closure.call(i);
14636             }
14637         } else
14638             throw new GroovyRuntimeException("The argument (" + to + 
14639                     ") to downto() cannot be greater than the value (" + self + ") it's called on.");
14640     }
14641 
14642     /**
14643      * Iterates from this number down to the given number, inclusive,
14644      * decrementing by one each time.
14645      *
14646      * @param self    a float
14647      * @param to the end number
14648      * @param closure the code to execute for each number
14649      * @since 1.0
14650      */
14651     public static void downto(float self, Number to, @ClosureParams(FirstParam.class) Closure closure) {
14652         float to1 = to.floatValue();
14653         if (self >= to1) {
14654             for (float i = self; i >= to1; i--) {
14655                 closure.call(i);
14656             }
14657         } else
14658             throw new GroovyRuntimeException("The argument (" + to + 
14659                     ") to downto() cannot be greater than the value (" + self + ") it's called on.");    }
14660 
14661     /**
14662      * Iterates from this number down to the given number, inclusive,
14663      * decrementing by one each time.
14664      *
14665      * @param self    a Float
14666      * @param to the end number
14667      * @param closure the code to execute for each number
14668      * @since 1.0
14669      */
14670     public static void downto(Float self, Number to, @ClosureParams(FirstParam.class) Closure closure) {
14671         float to1 = to.floatValue();
14672         if (self >= to1) {
14673             for (float i = self; i >= to1; i--) {
14674                 closure.call(i);
14675             }
14676         } else
14677             throw new GroovyRuntimeException("The argument (" + to + 
14678                     ") to downto() cannot be greater than the value (" + self + ") it's called on.");    }
14679 
14680     /**
14681      * Iterates from this number down to the given number, inclusive,
14682      * decrementing by one each time.
14683      *
14684      * @param self    a double
14685      * @param to the end number
14686      * @param closure the code to execute for each number
14687      * @since 1.0
14688      */
14689     public static void downto(double self, Number to, @ClosureParams(FirstParam.class) Closure closure) {
14690         double to1 = to.doubleValue();
14691         if (self >= to1) {
14692             for (double i = self; i >= to1; i--) {
14693                 closure.call(i);
14694             }
14695         } else
14696             throw new GroovyRuntimeException("The argument (" + to + 
14697                     ") to downto() cannot be greater than the value (" + self + ") it's called on.");    }
14698 
14699     /**
14700      * Iterates from this number down to the given number, inclusive,
14701      * decrementing by one each time.
14702      *
14703      * @param self    a Double
14704      * @param to the end number
14705      * @param closure the code to execute for each number
14706      * @since 1.0
14707      */
14708     public static void downto(Double self, Number to, @ClosureParams(FirstParam.class) Closure closure) {
14709         double to1 = to.doubleValue();
14710         if (self >= to1) {
14711             for (double i = self; i >= to1; i--) {
14712                 closure.call(i);
14713             }
14714         } else
14715             throw new GroovyRuntimeException("The argument (" + to + 
14716                     ") to downto() cannot be greater than the value (" + self + ") it's called on.");    }
14717 
14718     /**
14719      * Iterates from this number down to the given number, inclusive,
14720      * decrementing by one each time.
14721      *
14722      * @param self    a BigInteger
14723      * @param to the end number
14724      * @param closure the code to execute for each number
14725      * @since 1.0
14726      */
14727     public static void downto(BigInteger self, Number to, @ClosureParams(FirstParam.class) Closure closure) {
14728         if (to instanceof BigDecimal) {
14729             final BigDecimal one = BigDecimal.valueOf(10, 1);  // That's what you get for "1.0".
14730             final BigDecimal to1 = (BigDecimal) to;
14731             final BigDecimal selfD = new BigDecimal(self);
14732             if (selfD.compareTo(to1) >= 0) {
14733                 for (BigDecimal i = selfD; i.compareTo(to1) >= 0; i = i.subtract(one)) {
14734                     closure.call(i.toBigInteger());
14735                 }
14736             } else
14737                 throw new GroovyRuntimeException(
14738                         MessageFormat.format(
14739                                 "The argument ({0}) to downto() cannot be greater than the value ({1}) it''s called on.",
14740                                 to, self));
14741         } else if (to instanceof BigInteger) {
14742             final BigInteger one = BigInteger.valueOf(1);
14743             final BigInteger to1 = (BigInteger) to;
14744             if (self.compareTo(to1) >= 0) {
14745                 for (BigInteger i = self; i.compareTo(to1) >= 0; i = i.subtract(one)) {
14746                     closure.call(i);
14747                 }
14748             } else
14749                 throw new GroovyRuntimeException(
14750                         MessageFormat.format(
14751                                 "The argument ({0}) to downto() cannot be greater than the value ({1}) it''s called on.",
14752                                 to, self));
14753         } else {
14754             final BigInteger one = BigInteger.valueOf(1);
14755             final BigInteger to1 = new BigInteger(to.toString());
14756             if (self.compareTo(to1) >= 0) {
14757                 for (BigInteger i = self; i.compareTo(to1) >= 0; i = i.subtract(one)) {
14758                     closure.call(i);
14759                 }
14760             } else
14761                 throw new GroovyRuntimeException(
14762                         MessageFormat.format("The argument ({0}) to downto() cannot be greater than the value ({1}) it''s called on.",
14763                                 to, self));
14764         }
14765     }
14766 
14767     /**
14768      * Iterates from this number down to the given number, inclusive,
14769      * decrementing by one each time.  Each number is passed to the closure.
14770      * Example:
14771      * <pre>10.5.downto(0) {
14772      *   println it
14773      * }</pre>
14774      * Prints numbers 10.5, 9.5 ... to 0.5.
14775      *
14776      * @param self    a BigDecimal
14777      * @param to the end number
14778      * @param closure the code to execute for each number
14779      * @since 1.0
14780      */
14781     public static void downto(BigDecimal self, Number to, @ClosureParams(FirstParam.class) Closure closure) {
14782         final BigDecimal one = BigDecimal.valueOf(10, 1);  // Quick way to get "1.0".
14783         if (to instanceof BigDecimal) {
14784             BigDecimal to1 = (BigDecimal) to;
14785             if (self.compareTo(to1) >= 0) {
14786                 for (BigDecimal i = self; i.compareTo(to1) >= 0; i = i.subtract(one)) {
14787                     closure.call(i);
14788                 }
14789             } else
14790                 throw new GroovyRuntimeException("The argument (" + to + 
14791                         ") to downto() cannot be greater than the value (" + self + ") it's called on.");        } else if (to instanceof BigInteger) {
14792             BigDecimal to1 = new BigDecimal((BigInteger) to);
14793             if (self.compareTo(to1) >= 0) {
14794                 for (BigDecimal i = self; i.compareTo(to1) >= 0; i = i.subtract(one)) {
14795                     closure.call(i);
14796                 }
14797             } else
14798                 throw new GroovyRuntimeException("The argument (" + to + 
14799                         ") to downto() cannot be greater than the value (" + self + ") it's called on.");        } else {
14800             BigDecimal to1 = new BigDecimal(to.toString());
14801             if (self.compareTo(to1) >= 0) {
14802                 for (BigDecimal i = self; i.compareTo(to1) >= 0; i = i.subtract(one)) {
14803                     closure.call(i);
14804                 }
14805             } else
14806                 throw new GroovyRuntimeException("The argument (" + to + 
14807                         ") to downto() cannot be greater than the value (" + self + ") it's called on.");        }
14808     }
14809 
14810     /**
14811      * Iterates from this number up to the given number using a step increment.
14812      * Each intermediate number is passed to the given closure.  Example:
14813      * <pre>0.step( 10, 2 ) {
14814      *   println it
14815      * }</pre>
14816      * Prints even numbers 0 through 8.
14817      *
14818      * @param self       a Number to start with
14819      * @param to         a Number to go up to, exclusive
14820      * @param stepNumber a Number representing the step increment
14821      * @param closure    the closure to call
14822      * @since 1.0
14823      */
14824     public static void step(Number self, Number to, Number stepNumber, Closure closure) {
14825         if (self instanceof BigDecimal || to instanceof BigDecimal || stepNumber instanceof BigDecimal) {
14826             final BigDecimal zero = BigDecimal.valueOf(0, 1);  // Same as "0.0".
14827             BigDecimal self1 = (self instanceof BigDecimal) ? (BigDecimal) self : new BigDecimal(self.toString());
14828             BigDecimal to1 = (to instanceof BigDecimal) ? (BigDecimal) to : new BigDecimal(to.toString());
14829             BigDecimal stepNumber1 = (stepNumber instanceof BigDecimal) ? (BigDecimal) stepNumber : new BigDecimal(stepNumber.toString());
14830             if (stepNumber1.compareTo(zero) > 0 && to1.compareTo(self1) > 0) {
14831                 for (BigDecimal i = self1; i.compareTo(to1) < 0; i = i.add(stepNumber1)) {
14832                     closure.call(i);
14833                 }
14834             } else if (stepNumber1.compareTo(zero) < 0 && to1.compareTo(self1) < 0) {
14835                 for (BigDecimal i = self1; i.compareTo(to1) > 0; i = i.add(stepNumber1)) {
14836                     closure.call(i);
14837                 }
14838             } else if(self1.compareTo(to1) != 0)
14839                 throw new GroovyRuntimeException("Infinite loop in " + self1 + ".step(" + to1 + ", " + stepNumber1 + ")");
14840         } else if (self instanceof BigInteger || to instanceof BigInteger || stepNumber instanceof BigInteger) {
14841             final BigInteger zero = BigInteger.valueOf(0);
14842             BigInteger self1 = (self instanceof BigInteger) ? (BigInteger) self : new BigInteger(self.toString());
14843             BigInteger to1 = (to instanceof BigInteger) ? (BigInteger) to : new BigInteger(to.toString());
14844             BigInteger stepNumber1 = (stepNumber instanceof BigInteger) ? (BigInteger) stepNumber : new BigInteger(stepNumber.toString());
14845             if (stepNumber1.compareTo(zero) > 0 && to1.compareTo(self1) > 0) {
14846                 for (BigInteger i = self1; i.compareTo(to1) < 0; i = i.add(stepNumber1)) {
14847                     closure.call(i);
14848                 }
14849             } else if (stepNumber1.compareTo(zero) < 0 && to1.compareTo(self1) < 0) {
14850                 for (BigInteger i = self1; i.compareTo(to1) > 0; i = i.add(stepNumber1)) {
14851                     closure.call(i);
14852                 }
14853             } else if(self1.compareTo(to1) != 0)
14854                 throw new GroovyRuntimeException("Infinite loop in " + self1 + ".step(" + to1 + ", " + stepNumber1 + ")");
14855         } else {
14856             int self1 = self.intValue();
14857             int to1 = to.intValue();
14858             int stepNumber1 = stepNumber.intValue();
14859             if (stepNumber1 > 0 && to1 > self1) {
14860                 for (int i = self1; i < to1; i += stepNumber1) {
14861                     closure.call(i);
14862                 }
14863             } else if (stepNumber1 < 0 && to1 < self1) {
14864                 for (int i = self1; i > to1; i += stepNumber1) {
14865                     closure.call(i);
14866                 }
14867             } else if(self1 != to1)
14868                 throw new GroovyRuntimeException("Infinite loop in " + self1 + ".step(" + to1 + ", " + stepNumber1 + ")");
14869         }
14870     }
14871 
14872     /**
14873      * Get the absolute value
14874      *
14875      * @param number a Number
14876      * @return the absolute value of that Number
14877      * @since 1.0
14878      */
14879     //Note:  This method is NOT called if number is a BigInteger or BigDecimal because
14880     //those classes implement a method with a better exact match.
14881     public static int abs(Number number) {
14882         return Math.abs(number.intValue());
14883     }
14884 
14885     /**
14886      * Get the absolute value
14887      *
14888      * @param number a Long
14889      * @return the absolute value of that Long
14890      * @since 1.0
14891      */
14892     public static long abs(Long number) {
14893         return Math.abs(number.longValue());
14894     }
14895 
14896     /**
14897      * Get the absolute value
14898      *
14899      * @param number a Float
14900      * @return the absolute value of that Float
14901      * @since 1.0
14902      */
14903     public static float abs(Float number) {
14904         return Math.abs(number.floatValue());
14905     }
14906 
14907     /**
14908      * Get the absolute value
14909      *
14910      * @param number a Double
14911      * @return the absolute value of that Double
14912      * @since 1.0
14913      */
14914     public static double abs(Double number) {
14915         return Math.abs(number);
14916     }
14917 
14918     /**
14919      * Round the value
14920      *
14921      * @param number a Float
14922      * @return the rounded value of that Float
14923      * @since 1.0
14924      */
14925     public static int round(Float number) {
14926         return Math.round(number.floatValue());
14927     }
14928 
14929     /**
14930      * Round the value
14931      *
14932      * @param number a Float
14933      * @param precision the number of decimal places to keep
14934      * @return the Float rounded to the number of decimal places specified by precision
14935      * @since 1.6.0
14936      */
14937     public static float round(Float number, int precision) {
14938         return (float)(Math.floor(number.doubleValue()*Math.pow(10,precision)+0.5)/Math.pow(10,precision));
14939     }
14940 
14941     /**
14942      * Truncate the value
14943      *
14944      * @param number a Float
14945      * @param precision the number of decimal places to keep
14946      * @return the Float truncated to the number of decimal places specified by precision
14947      * @since 1.6.0
14948      */
14949     public static float trunc(Float number, int precision) {
14950         return (float)(Math.floor(number.doubleValue()*Math.pow(10,precision))/Math.pow(10,precision));
14951     }
14952 
14953     /**
14954      * Truncate the value
14955      *
14956      * @param number a Double
14957      * @return the Double truncated to 0 decimal places (i.e. a synonym for floor)
14958      * @since 1.6.0
14959      */
14960     public static float trunc(Float number) {
14961         return (float)Math.floor(number.doubleValue());
14962     }
14963 
14964     /**
14965      * Round the value
14966      *
14967      * @param number a Double
14968      * @return the rounded value of that Double
14969      * @since 1.0
14970      */
14971     public static long round(Double number) {
14972         return Math.round(number);
14973     }
14974 
14975     /**
14976      * Round the value
14977      *
14978      * @param number a Double
14979      * @param precision the number of decimal places to keep
14980      * @return the Double rounded to the number of decimal places specified by precision
14981      * @since 1.6.4
14982      */
14983     public static double round(Double number, int precision) {
14984         return Math.floor(number *Math.pow(10,precision)+0.5)/Math.pow(10,precision);
14985     }
14986 
14987     /**
14988      * Truncate the value
14989      *
14990      * @param number a Double
14991      * @return the Double truncated to 0 decimal places (i.e. a synonym for floor)
14992      * @since 1.6.4
14993      */
14994     public static double trunc(Double number) {
14995         return Math.floor(number);
14996     }
14997 
14998     /**
14999      * Truncate the value
15000      *
15001      * @param number a Double
15002      * @param precision the number of decimal places to keep
15003      * @return the Double truncated to the number of decimal places specified by precision
15004      * @since 1.6.4
15005      */
15006     public static double trunc(Double number, int precision) {
15007         return Math.floor(number *Math.pow(10,precision))/Math.pow(10,precision);
15008     }
15009 
15010     /**
15011      * Determine if a Character is uppercase.
15012      * Synonym for 'Character.isUpperCase(this)'.
15013      *
15014      * @param self a Character
15015      * @return true if the character is uppercase
15016      * @see java.lang.Character#isUpperCase(char)
15017      * @since 1.5.7
15018      */
15019     public static boolean isUpperCase(Character self) {
15020         return Character.isUpperCase(self);
15021     }
15022 
15023     /**
15024      * Determine if a Character is lowercase.
15025      * Synonym for 'Character.isLowerCase(this)'.
15026      *
15027      * @param self a Character
15028      * @return true if the character is lowercase
15029      * @see java.lang.Character#isLowerCase(char)
15030      * @since 1.5.7
15031      */
15032     public static boolean isLowerCase(Character self) {
15033         return Character.isLowerCase(self);
15034     }
15035 
15036     /**
15037      * Determines if a character is a letter.
15038      * Synonym for 'Character.isLetter(this)'.
15039      *
15040      * @param self a Character
15041      * @return true if the character is a letter
15042      * @see java.lang.Character#isLetter(char)
15043      * @since 1.5.7
15044      */
15045     public static boolean isLetter(Character self) {
15046         return Character.isLetter(self);
15047     }
15048 
15049     /**
15050      * Determines if a character is a digit.
15051      * Synonym for 'Character.isDigit(this)'.
15052      *
15053      * @param self a Character
15054      * @return true if the character is a digit
15055      * @see java.lang.Character#isDigit(char)
15056      * @since 1.5.7
15057      */
15058     public static boolean isDigit(Character self) {
15059         return Character.isDigit(self);
15060     }
15061 
15062     /**
15063      * Determines if a character is a letter or digit.
15064      * Synonym for 'Character.isLetterOrDigit(this)'.
15065      *
15066      * @param self a Character
15067      * @return true if the character is a letter or digit
15068      * @see java.lang.Character#isLetterOrDigit(char)
15069      * @since 1.5.7
15070      */
15071     public static boolean isLetterOrDigit(Character self) {
15072         return Character.isLetterOrDigit(self);
15073     }
15074 
15075     /**
15076      * Determines if a character is a whitespace character.
15077      * Synonym for 'Character.isWhitespace(this)'.
15078      *
15079      * @param self a Character
15080      * @return true if the character is a whitespace character
15081      * @see java.lang.Character#isWhitespace(char)
15082      * @since 1.5.7
15083      */
15084     public static boolean isWhitespace(Character self) {
15085         return Character.isWhitespace(self);
15086     }
15087 
15088     /**
15089      * Converts the character to uppercase.
15090      * Synonym for 'Character.toUpperCase(this)'.
15091      *
15092      * @param self a Character to convert
15093      * @return  the uppercase equivalent of the character, if any;
15094      *          otherwise, the character itself.
15095      * @see     java.lang.Character#isUpperCase(char)
15096      * @see     java.lang.String#toUpperCase()
15097      * @since 1.5.7
15098      */
15099     public static char toUpperCase(Character self) {
15100         return Character.toUpperCase(self);
15101     }
15102 
15103     /**
15104      * Converts the character to lowercase.
15105      * Synonym for 'Character.toLowerCase(this)'.
15106      *
15107      * @param self a Character to convert
15108      * @return  the lowercase equivalent of the character, if any;
15109      *          otherwise, the character itself.
15110      * @see     java.lang.Character#isLowerCase(char)
15111      * @see     java.lang.String#toLowerCase()
15112      * @since 1.5.7
15113      */
15114     public static char toLowerCase(Character self) {
15115         return Character.toLowerCase(self);
15116     }
15117 
15118     /**
15119      * Transform a Number into an Integer
15120      *
15121      * @param self a Number
15122      * @return an Integer
15123      * @since 1.0
15124      */
15125     public static Integer toInteger(Number self) {
15126         return self.intValue();
15127     }
15128 
15129     /**
15130      * Transform a Number into a Long
15131      *
15132      * @param self a Number
15133      * @return an Long
15134      * @since 1.0
15135      */
15136     public static Long toLong(Number self) {
15137         return self.longValue();
15138     }
15139 
15140     /**
15141      * Transform a Number into a Float
15142      *
15143      * @param self a Number
15144      * @return an Float
15145      * @since 1.0
15146      */
15147     public static Float toFloat(Number self) {
15148         return self.floatValue();
15149     }
15150 
15151     /**
15152      * Transform a Number into a Double
15153      *
15154      * @param self a Number
15155      * @return an Double
15156      * @since 1.0
15157      */
15158     public static Double toDouble(Number self) {
15159         // Conversions in which all decimal digits are known to be good.
15160         if ((self instanceof Double)
15161                 || (self instanceof Long)
15162                 || (self instanceof Integer)
15163                 || (self instanceof Short)
15164                 || (self instanceof Byte))
15165         {
15166             return self.doubleValue();
15167         }
15168 
15169         // Chances are this is a Float or a Big.
15170         // With Float we're extending binary precision and that gets ugly in decimal.
15171         // If we used Float.doubleValue() on 0.1f we get 0.10000000149011612.
15172         // Note that this is different than casting '(double) 0.1f' which will do the
15173         // binary extension just like in Java.
15174         // With Bigs and other unknowns, this is likely to be the same.
15175 
15176         return Double.valueOf(self.toString());
15177     }
15178 
15179     /**
15180      * Transform a Number into a BigDecimal
15181      *
15182      * @param self a Number
15183      * @return an BigDecimal
15184      * @since 1.0
15185      */
15186     public static BigDecimal toBigDecimal(Number self) {
15187         // Quick method for scalars.
15188         if ((self instanceof Long)
15189                 || (self instanceof Integer)
15190                 || (self instanceof Short)
15191                 || (self instanceof Byte))
15192         {
15193             return BigDecimal.valueOf(self.longValue());
15194         }
15195 
15196         return new BigDecimal(self.toString());
15197     }
15198 
15199     /**
15200      * Transform this number to a the given type, using the 'as' operator.  The
15201      * following types are supported in addition to the default
15202      * {@link #asType(java.lang.Object, java.lang.Class)}:
15203      * <ul>
15204      *  <li>BigDecimal</li>
15205      *  <li>BigInteger</li>
15206      *  <li>Double</li>
15207      *  <li>Float</li>
15208      * </ul>
15209      * @param self this number
15210      * @param c the desired type of the transformed result
15211      * @return an instance of the given type
15212      * @since 1.0
15213      */
15214     @SuppressWarnings("unchecked")
15215     public static <T> T asType(Number self, Class<T> c) {
15216         if (c == BigDecimal.class) {
15217             return (T) toBigDecimal(self);
15218         } else if (c == BigInteger.class) {
15219             return (T) toBigInteger(self);
15220         } else if (c == Double.class) {
15221             return (T) toDouble(self);
15222         } else if (c == Float.class) {
15223             return (T) toFloat(self);
15224         }
15225         return asType((Object) self, c);
15226     }
15227 
15228     /**
15229      * Transform this Number into a BigInteger.
15230      *
15231      * @param self a Number
15232      * @return an BigInteger
15233      * @since 1.0
15234      */
15235     public static BigInteger toBigInteger(Number self) {
15236         if (self instanceof BigInteger) {
15237             return (BigInteger) self;
15238         } else if (self instanceof BigDecimal) {
15239             return ((BigDecimal) self).toBigInteger();
15240         } else if (self instanceof Double) {
15241             return new BigDecimal((Double)self).toBigInteger();
15242         } else if (self instanceof Float) {
15243             return new BigDecimal((Float)self).toBigInteger();
15244         } else {
15245             return new BigInteger(Long.toString(self.longValue()));
15246         }
15247     }
15248 
15249     // Boolean based methods
15250     //-------------------------------------------------------------------------
15251 
15252 
15253     /**
15254      * Logical conjunction of two boolean operators.
15255      *
15256      * @param left left operator
15257      * @param right right operator
15258      * @return result of logical conjunction
15259      * @since 1.0
15260      */
15261     public static Boolean and(Boolean left, Boolean right) {
15262         return left && right;
15263     }
15264 
15265     /**
15266      * Logical disjunction of two boolean operators
15267      *
15268      * @param left left operator
15269      * @param right right operator
15270      * @return result of logical disjunction
15271      * @since 1.0
15272      */
15273     public static Boolean or(Boolean left, Boolean right) {
15274         return left || right;
15275     }
15276 
15277     /**
15278      * Logical implication of two boolean operators
15279      *
15280      * @param left left operator
15281      * @param right right operator
15282      * @return result of logical implication
15283      * @since 1.8.3
15284      */
15285     public static Boolean implies(Boolean left, Boolean right) {
15286         return !left || right;
15287     }
15288 
15289     /**
15290      * Exclusive disjunction of two boolean operators
15291      *
15292      * @param left left operator
15293      * @param right right operator
15294      * @return result of exclusive disjunction
15295      * @since 1.0
15296      */
15297     public static Boolean xor(Boolean left, Boolean right) {
15298         return left ^ right;
15299     }
15300 
15301 //    public static Boolean negate(Boolean left) {
15302 //        return Boolean.valueOf(!left.booleanValue());
15303 //    }
15304 
15305     /**
15306      * Allows a simple syntax for using timers.  This timer will execute the
15307      * given closure after the given delay.
15308      *
15309      * @param timer   a timer object
15310      * @param delay   the delay in milliseconds before running the closure code
15311      * @param closure the closure to invoke
15312      * @return The timer task which has been scheduled.
15313      * @since 1.5.0
15314      */
15315     public static TimerTask runAfter(Timer timer, int delay, final Closure closure) {
15316         TimerTask timerTask = new TimerTask() {
15317             public void run() {
15318                 closure.call();
15319             }
15320         };
15321         timer.schedule(timerTask, delay);
15322         return timerTask;
15323     }
15324 
15325     /**
15326      * Traverse through each byte of this Byte array. Alias for each.
15327      *
15328      * @param self    a Byte array
15329      * @param closure a closure
15330      * @see #each(java.lang.Object, groovy.lang.Closure)
15331      * @since 1.5.5
15332      */
15333     public static void eachByte(Byte[] self, @ClosureParams(FirstParam.Component.class) Closure closure) {
15334         each(self, closure);
15335     }
15336 
15337     /**
15338      * Traverse through each byte of this byte array. Alias for each.
15339      *
15340      * @param self    a byte array
15341      * @param closure a closure
15342      * @see #each(java.lang.Object, groovy.lang.Closure)
15343      * @since 1.5.5
15344      */
15345     public static void eachByte(byte[] self, @ClosureParams(FirstParam.Component.class) Closure closure) {
15346         each(self, closure);
15347     }
15348 
15349     /**
15350      * Iterates over the elements of an iterable collection of items and returns
15351      * the index of the first item that matches the condition specified in the closure.
15352      *
15353      * @param self    the iteration object over which to iterate
15354      * @param closure the filter to perform a match on the collection
15355      * @return an integer that is the index of the first matched object or -1 if no match was found
15356      * @since 1.0
15357      */
15358     public static int findIndexOf(Object self, Closure closure) {
15359         return findIndexOf(self, 0, closure);
15360     }
15361 
15362     /**
15363      * Iterates over the elements of an iterable collection of items, starting from a
15364      * specified startIndex, and returns the index of the first item that matches the
15365      * condition specified in the closure.
15366      *
15367      * @param self       the iteration object over which to iterate
15368      * @param startIndex start matching from this index
15369      * @param closure    the filter to perform a match on the collection
15370      * @return an integer that is the index of the first matched object or -1 if no match was found
15371      * @since 1.5.0
15372      */
15373     public static int findIndexOf(Object self, int startIndex, Closure closure) {
15374         int result = -1;
15375         int i = 0;
15376         BooleanClosureWrapper bcw = new BooleanClosureWrapper(closure);
15377         for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext(); i++) {
15378             Object value = iter.next();
15379             if (i < startIndex) {
15380                 continue;
15381             }
15382             if (bcw.call(value)) {
15383                 result = i;
15384                 break;
15385             }
15386         }
15387         return result;
15388     }
15389 
15390     /**
15391      * Iterates over the elements of an iterable collection of items and returns
15392      * the index of the last item that matches the condition specified in the closure.
15393      *
15394      * @param self    the iteration object over which to iterate
15395      * @param closure the filter to perform a match on the collection
15396      * @return an integer that is the index of the last matched object or -1 if no match was found
15397      * @since 1.5.2
15398      */
15399     public static int findLastIndexOf(Object self, Closure closure) {
15400         return findLastIndexOf(self, 0, closure);
15401     }
15402 
15403     /**
15404      * Iterates over the elements of an iterable collection of items, starting
15405      * from a specified startIndex, and returns the index of the last item that
15406      * matches the condition specified in the closure.
15407      *
15408      * @param self       the iteration object over which to iterate
15409      * @param startIndex start matching from this index
15410      * @param closure    the filter to perform a match on the collection
15411      * @return an integer that is the index of the last matched object or -1 if no match was found
15412      * @since 1.5.2
15413      */
15414     public static int findLastIndexOf(Object self, int startIndex, Closure closure) {
15415         int result = -1;
15416         int i = 0;
15417         BooleanClosureWrapper bcw = new BooleanClosureWrapper(closure);
15418         for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext(); i++) {
15419             Object value = iter.next();
15420             if (i < startIndex) {
15421                 continue;
15422             }
15423             if (bcw.call(value)) {
15424                 result = i;
15425             }
15426         }
15427         return result;
15428     }
15429 
15430     /**
15431      * Iterates over the elements of an iterable collection of items and returns
15432      * the index values of the items that match the condition specified in the closure.
15433      *
15434      * @param self    the iteration object over which to iterate
15435      * @param closure the filter to perform a match on the collection
15436      * @return a list of numbers corresponding to the index values of all matched objects
15437      * @since 1.5.2
15438      */
15439     public static List<Number> findIndexValues(Object self, Closure closure) {
15440         return findIndexValues(self, 0, closure);
15441     }
15442 
15443     /**
15444      * Iterates over the elements of an iterable collection of items, starting from
15445      * a specified startIndex, and returns the index values of the items that match
15446      * the condition specified in the closure.
15447      *
15448      * @param self       the iteration object over which to iterate
15449      * @param startIndex start matching from this index
15450      * @param closure    the filter to perform a match on the collection
15451      * @return a list of numbers corresponding to the index values of all matched objects
15452      * @since 1.5.2
15453      */
15454     public static List<Number> findIndexValues(Object self, Number startIndex, Closure closure) {
15455         List<Number> result = new ArrayList<Number>();
15456         long count = 0;
15457         long startCount = startIndex.longValue();
15458         BooleanClosureWrapper bcw = new BooleanClosureWrapper(closure);
15459         for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext(); count++) {
15460             Object value = iter.next();
15461             if (count < startCount) {
15462                 continue;
15463             }
15464             if (bcw.call(value)) {
15465                 result.add(count);
15466             }
15467         }
15468         return result;
15469     }
15470 
15471     /**
15472      * Iterates through the classloader parents until it finds a loader with a class
15473      * named "org.codehaus.groovy.tools.RootLoader". If there is no such class
15474      * <code>null</code> will be returned. The name is used for comparison because
15475      * a direct comparison using == may fail as the class may be loaded through
15476      * different classloaders.
15477      *
15478      * @param self a ClassLoader
15479      * @return the rootLoader for the ClassLoader
15480      * @see org.codehaus.groovy.tools.RootLoader
15481      * @since 1.5.0
15482      */
15483     public static ClassLoader getRootLoader(ClassLoader self) {
15484         while (true) {
15485             if (self == null) return null;
15486             if (isRootLoaderClassOrSubClass(self)) return self;
15487             self = self.getParent();
15488         }
15489     }
15490 
15491     private static boolean isRootLoaderClassOrSubClass(ClassLoader self) {
15492         Class current = self.getClass();
15493         while(!current.getName().equals(Object.class.getName())) {
15494             if(current.getName().equals(RootLoader.class.getName())) return true;
15495             current = current.getSuperclass();
15496         }
15497 
15498         return false;
15499     }
15500 
15501 
15502     /**
15503      * Converts a given object to a type. This method is used through
15504      * the "as" operator and is overloadable as any other operator.
15505      *
15506      * @param obj  the object to convert
15507      * @param type the goal type
15508      * @return the resulting object
15509      * @since 1.0
15510      */
15511     @SuppressWarnings("unchecked")
15512     public static <T> T asType(Object obj, Class<T> type) {
15513         if (String.class == type) {
15514             return (T) InvokerHelper.toString(obj);
15515         }
15516 
15517         // fall back to cast
15518         try {
15519             return (T) DefaultTypeTransformation.castToType(obj, type);
15520         }
15521         catch (GroovyCastException e) {
15522             MetaClass mc = InvokerHelper.getMetaClass(obj);
15523             if (mc instanceof ExpandoMetaClass) {
15524                 ExpandoMetaClass emc = (ExpandoMetaClass) mc;
15525                 Object mixedIn = emc.castToMixedType(obj, type);
15526                 if (mixedIn != null)
15527                     return (T) mixedIn;
15528             }
15529             if (type.isInterface()) {
15530                 try {
15531                     List<Class> interfaces = new ArrayList<Class>();
15532                     interfaces.add(type);
15533                     return (T) ProxyGenerator.INSTANCE.instantiateDelegate(interfaces, obj);
15534                 } catch (GroovyRuntimeException cause) {
15535                     // ignore
15536                 }
15537             }
15538             throw e;
15539         }
15540     }
15541 
15542     private static Object asArrayType(Object object, Class type) {
15543         if (type.isAssignableFrom(object.getClass())) {
15544             return object;
15545         }
15546         Collection list = DefaultTypeTransformation.asCollection(object);
15547         int size = list.size();
15548         Class elementType = type.getComponentType();
15549         Object array = Array.newInstance(elementType, size);
15550         int idx = 0;
15551 
15552         if (boolean.class.equals(elementType)) {
15553             for (Iterator iter = list.iterator(); iter.hasNext(); idx++) {
15554                 Object element = iter.next();
15555                 Array.setBoolean(array, idx, (Boolean) InvokerHelper.invokeStaticMethod(DefaultGroovyMethods.class, "asType", new Object[]{element, boolean.class}));
15556             }
15557         } else if (byte.class.equals(elementType)) {
15558             for (Iterator iter = list.iterator(); iter.hasNext(); idx++) {
15559                 Object element = iter.next();
15560                 Array.setByte(array, idx, (Byte) InvokerHelper.invokeStaticMethod(DefaultGroovyMethods.class, "asType", new Object[]{element, byte.class}));
15561             }
15562         } else if (char.class.equals(elementType)) {
15563             for (Iterator iter = list.iterator(); iter.hasNext(); idx++) {
15564                 Object element = iter.next();
15565                 Array.setChar(array, idx, (Character) InvokerHelper.invokeStaticMethod(DefaultGroovyMethods.class, "asType", new Object[]{element, char.class}));
15566             }
15567         } else if (double.class.equals(elementType)) {
15568             for (Iterator iter = list.iterator(); iter.hasNext(); idx++) {
15569                 Object element = iter.next();
15570                 Array.setDouble(array, idx, (Double) InvokerHelper.invokeStaticMethod(DefaultGroovyMethods.class, "asType", new Object[]{element, double.class}));
15571             }
15572         } else if (float.class.equals(elementType)) {
15573             for (Iterator iter = list.iterator(); iter.hasNext(); idx++) {
15574                 Object element = iter.next();
15575                 Array.setFloat(array, idx, (Float) InvokerHelper.invokeStaticMethod(DefaultGroovyMethods.class, "asType", new Object[]{element, float.class}));
15576             }
15577         } else if (int.class.equals(elementType)) {
15578             for (Iterator iter = list.iterator(); iter.hasNext(); idx++) {
15579                 Object element = iter.next();
15580                 Array.setInt(array, idx, (Integer) InvokerHelper.invokeStaticMethod(DefaultGroovyMethods.class, "asType", new Object[]{element, int.class}));
15581             }
15582         } else if (long.class.equals(elementType)) {
15583             for (Iterator iter = list.iterator(); iter.hasNext(); idx++) {
15584                 Object element = iter.next();
15585                 Array.setLong(array, idx, (Long) InvokerHelper.invokeStaticMethod(DefaultGroovyMethods.class, "asType", new Object[]{element, long.class}));
15586             }
15587         } else if (short.class.equals(elementType)) {
15588             for (Iterator iter = list.iterator(); iter.hasNext(); idx++) {
15589                 Object element = iter.next();
15590                 Array.setShort(array, idx, (Short) InvokerHelper.invokeStaticMethod(DefaultGroovyMethods.class, "asType", new Object[]{element, short.class}));
15591             }
15592         } else for (Iterator iter = list.iterator(); iter.hasNext(); idx++) {
15593             Object element = iter.next();
15594             Array.set(array, idx, InvokerHelper.invokeStaticMethod(DefaultGroovyMethods.class, "asType", new Object[]{element, elementType}));
15595         }
15596         return array;
15597     }
15598 
15599     /**
15600      * Convenience method to dynamically create a new instance of this
15601      * class.  Calls the default constructor.
15602      *
15603      * @param c a class
15604      * @return a new instance of this class
15605      * @since 1.0
15606      */
15607     @SuppressWarnings("unchecked")
15608     public static <T> T newInstance(Class<T> c) {
15609         return (T) InvokerHelper.invokeConstructorOf(c, null);
15610     }
15611 
15612     /**
15613      * Helper to construct a new instance from the given arguments.
15614      * The constructor is called based on the number and types in the
15615      * args array.  Use <code>newInstance(null)</code> or simply
15616      * <code>newInstance()</code> for the default (no-arg) constructor.
15617      *
15618      * @param c    a class
15619      * @param args the constructor arguments
15620      * @return a new instance of this class.
15621      * @since 1.0
15622      */
15623     @SuppressWarnings("unchecked")
15624     public static <T> T newInstance(Class<T> c, Object[] args) {
15625         if (args == null) args = new Object[]{null};
15626         return (T) InvokerHelper.invokeConstructorOf(c, args);
15627     }
15628 
15629     /**
15630      * Adds a "metaClass" property to all class objects so you can use the syntax
15631      * <code>String.metaClass.myMethod = { println "foo" }</code>
15632      *
15633      * @param c The java.lang.Class instance
15634      * @return An MetaClass instance
15635      * @since 1.5.0
15636      */
15637     public static MetaClass getMetaClass(Class c) {
15638         MetaClassRegistry metaClassRegistry = GroovySystem.getMetaClassRegistry();
15639         MetaClass mc = metaClassRegistry.getMetaClass(c);
15640         if (mc instanceof ExpandoMetaClass
15641                 || mc instanceof DelegatingMetaClass && ((DelegatingMetaClass) mc).getAdaptee() instanceof ExpandoMetaClass)
15642             return mc;
15643         else {
15644             return new HandleMetaClass(mc);
15645         }
15646     }
15647 
15648     /**
15649      * Obtains a MetaClass for an object either from the registry or in the case of
15650      * a GroovyObject from the object itself.
15651      *
15652      * @param obj The object in question
15653      * @return The MetaClass
15654      * @since 1.5.0
15655      */
15656     public static MetaClass getMetaClass(Object obj) {
15657         MetaClass mc = InvokerHelper.getMetaClass(obj);
15658         return new HandleMetaClass(mc, obj);
15659     }
15660 
15661     /**
15662      * Obtains a MetaClass for an object either from the registry or in the case of
15663      * a GroovyObject from the object itself.
15664      *
15665      * @param obj The object in question
15666      * @return The MetaClass
15667      * @since 1.6.0
15668      */
15669     public static MetaClass getMetaClass(GroovyObject obj) {
15670         // we need this method as trick to guarantee correct method selection
15671         return getMetaClass((Object)obj);
15672     }
15673 
15674     /**
15675      * Sets the metaclass for a given class.
15676      *
15677      * @param self the class whose metaclass we wish to set
15678      * @param metaClass the new MetaClass
15679      * @since 1.6.0
15680      */
15681     public static void setMetaClass(Class self, MetaClass metaClass) {
15682         final MetaClassRegistry metaClassRegistry = GroovySystem.getMetaClassRegistry();
15683         if (metaClass == null)
15684             metaClassRegistry.removeMetaClass(self);
15685         else {
15686             if (metaClass instanceof HandleMetaClass) {
15687                 metaClassRegistry.setMetaClass(self, ((HandleMetaClass)metaClass).getAdaptee());
15688             } else {
15689                 metaClassRegistry.setMetaClass(self, metaClass);
15690             }
15691             if (self==NullObject.class) {
15692                 NullObject.getNullObject().setMetaClass(metaClass);
15693             }
15694         }
15695     }
15696 
15697     /**
15698      * Set the metaclass for an object.
15699      * @param self the object whose metaclass we want to set
15700      * @param metaClass the new metaclass value
15701      * @since 1.6.0
15702      */
15703     public static void setMetaClass(Object self, MetaClass metaClass) {
15704         if (metaClass instanceof HandleMetaClass)
15705             metaClass = ((HandleMetaClass)metaClass).getAdaptee();
15706 
15707         if (self instanceof Class) {
15708             GroovySystem.getMetaClassRegistry().setMetaClass((Class) self, metaClass);
15709         } else {
15710             ((MetaClassRegistryImpl)GroovySystem.getMetaClassRegistry()).setMetaClass(self, metaClass);
15711         }
15712     }
15713 
15714     /**
15715      * Set the metaclass for a GroovyObject.
15716      * @param self the object whose metaclass we want to set
15717      * @param metaClass the new metaclass value
15718      * @since 2.0.0
15719      */
15720     public static void setMetaClass(GroovyObject self, MetaClass metaClass) {
15721         // this method was introduced as to prevent from a stack overflow, described in GROOVY-5285
15722         if (metaClass instanceof HandleMetaClass)
15723             metaClass = ((HandleMetaClass)metaClass).getAdaptee();
15724 
15725         self.setMetaClass(metaClass);
15726         disablePrimitiveOptimization(self);
15727     }
15728 
15729     private static void disablePrimitiveOptimization(Object self) {
15730         Field sdyn;
15731         Class c = self.getClass();
15732         try {
15733             sdyn = c.getDeclaredField(Verifier.STATIC_METACLASS_BOOL);
15734             sdyn.setBoolean(null, true);
15735         } catch (Throwable e) {
15736             //DO NOTHING
15737         }
15738     }
15739 
15740     /**
15741      * Sets/updates the metaclass for a given class to a closure.
15742      *
15743      * @param self the class whose metaclass we wish to update
15744      * @param closure the closure representing the new metaclass
15745      * @return the new metaclass value
15746      * @throws GroovyRuntimeException if the metaclass can't be set for this class
15747      * @since 1.6.0
15748      */
15749     public static MetaClass metaClass (Class self, Closure closure){
15750         MetaClassRegistry metaClassRegistry = GroovySystem.getMetaClassRegistry();
15751         MetaClass mc = metaClassRegistry.getMetaClass(self);
15752 
15753         if (mc instanceof ExpandoMetaClass) {
15754             ((ExpandoMetaClass) mc).define(closure);
15755             return mc;
15756         }
15757         else {
15758             if (mc instanceof DelegatingMetaClass && ((DelegatingMetaClass) mc).getAdaptee() instanceof ExpandoMetaClass) {
15759                 ((ExpandoMetaClass)((DelegatingMetaClass) mc).getAdaptee()).define(closure);
15760                 return mc;
15761             }
15762             else {
15763                 if (mc instanceof DelegatingMetaClass && ((DelegatingMetaClass) mc).getAdaptee().getClass() == MetaClassImpl.class) {
15764                     ExpandoMetaClass emc =  new ExpandoMetaClass(self, false, true);
15765                     emc.initialize();
15766                     emc.define(closure);
15767                     ((DelegatingMetaClass) mc).setAdaptee(emc);
15768                     return mc;
15769                 }
15770                 else {
15771                     if (mc.getClass() == MetaClassImpl.class) {
15772                         // default case
15773                         mc = new ExpandoMetaClass(self, false, true);
15774                         mc.initialize();
15775                         ((ExpandoMetaClass)mc).define(closure);
15776                         metaClassRegistry.setMetaClass(self, mc);
15777                         return mc;
15778                     }
15779                     else {
15780                         throw new GroovyRuntimeException("Can't add methods to custom meta class " + mc);
15781                     }
15782                 }
15783             }
15784         }
15785     }
15786 
15787     /**
15788      * Sets/updates the metaclass for a given object to a closure.
15789      *
15790      * @param self the object whose metaclass we wish to update
15791      * @param closure the closure representing the new metaclass
15792      * @return the new metaclass value
15793      * @throws GroovyRuntimeException if the metaclass can't be set for this object
15794      * @since 1.6.0
15795      */
15796     public static MetaClass metaClass (Object self, Closure closure){
15797         MetaClass emc = hasPerInstanceMetaClass(self);
15798         if (emc == null) {
15799             final ExpandoMetaClass metaClass = new ExpandoMetaClass(self.getClass(), false, true);
15800             metaClass.initialize();
15801             metaClass.define(closure);
15802             if (self instanceof GroovyObject) {
15803                 setMetaClass((GroovyObject)self, metaClass);
15804             } else {
15805                 setMetaClass(self, metaClass);
15806             }
15807             return metaClass;
15808         }
15809         else {
15810             if (emc instanceof ExpandoMetaClass) {
15811                 ((ExpandoMetaClass)emc).define(closure);
15812                 return emc;
15813             }
15814             else {
15815                 if (emc instanceof DelegatingMetaClass && ((DelegatingMetaClass)emc).getAdaptee() instanceof ExpandoMetaClass) {
15816                     ((ExpandoMetaClass)((DelegatingMetaClass)emc).getAdaptee()).define(closure);
15817                     return emc;
15818                 }
15819                 else {
15820                     throw new RuntimeException("Can't add methods to non-ExpandoMetaClass " + emc);
15821                 }
15822             }
15823         }
15824     }
15825 
15826     private static MetaClass hasPerInstanceMetaClass(Object object) {
15827         if (object instanceof GroovyObject) {
15828             MetaClass mc = ((GroovyObject)object).getMetaClass();
15829             if (mc == GroovySystem.getMetaClassRegistry().getMetaClass(object.getClass()) || mc.getClass() == MetaClassImpl.class)
15830                 return null;
15831             else
15832                 return mc;
15833         }
15834         else {
15835             ClassInfo info = ClassInfo.getClassInfo(object.getClass());
15836             info.lock();
15837             try {
15838                 return info.getPerInstanceMetaClass(object);
15839             }
15840             finally {
15841                 info.unlock();
15842             }
15843         }
15844     }
15845 
15846     /**
15847      * Attempts to create an Iterator for the given object by first
15848      * converting it to a Collection.
15849      *
15850      * @param a an array
15851      * @return an Iterator for the given Array.
15852      * @see org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation#asCollection(java.lang.Object[])
15853      * @since 1.6.4
15854      */
15855     public static <T> Iterator<T> iterator(T[] a) {
15856         return DefaultTypeTransformation.asCollection(a).iterator();
15857     }
15858 
15859     /**
15860      * Attempts to create an Iterator for the given object by first
15861      * converting it to a Collection.
15862      *
15863      * @param o an object
15864      * @return an Iterator for the given Object.
15865      * @see org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation#asCollection(java.lang.Object)
15866      * @since 1.0
15867      */
15868     public static Iterator iterator(Object o) {
15869         return DefaultTypeTransformation.asCollection(o).iterator();
15870     }
15871 
15872     /**
15873      * Allows an Enumeration to behave like an Iterator.  Note that the
15874      * {@link java.util.Iterator#remove() remove()} method is unsupported since the
15875      * underlying Enumeration does not provide a mechanism for removing items.
15876      *
15877      * @param enumeration an Enumeration object
15878      * @return an Iterator for the given Enumeration
15879      * @since 1.0
15880      */
15881     public static <T> Iterator<T> iterator(final Enumeration<T> enumeration) {
15882         return new Iterator<T>() {
15883             private T last;
15884 
15885             public boolean hasNext() {
15886                 return enumeration.hasMoreElements();
15887             }
15888 
15889             public T next() {
15890                 last = enumeration.nextElement();
15891                 return last;
15892             }
15893 
15894             public void remove() {
15895                 throw new UnsupportedOperationException("Cannot remove() from an Enumeration");
15896             }
15897         };
15898     }
15899 
15900     /**
15901      * An identity function for iterators, supporting 'duck-typing' when trying to get an
15902      * iterator for each object within a collection, some of which may already be iterators.
15903      *
15904      * @param self an iterator object
15905      * @return itself
15906      * @since 1.5.0
15907      */
15908     public static <T> Iterator<T> iterator(Iterator<T> self) {
15909         return self;
15910     }
15911 
15912     /**
15913      * <p>Returns an object satisfying Groovy truth if the implementing MetaClass responds to
15914      * a method with the given name and arguments types.
15915      *
15916      * <p>Note that this method's return value is based on realised methods and does not take into account
15917      * objects or classes that implement invokeMethod or methodMissing
15918      *
15919      * <p>This method is "safe" in that it will always return a value and never throw an exception
15920      *
15921      * @param self The object to inspect
15922      * @param name The name of the method of interest
15923      * @param argTypes The argument types to match against
15924      * @return A List of MetaMethods matching the argument types which will be empty if no matching methods exist
15925      * @see groovy.lang.MetaObjectProtocol#respondsTo(java.lang.Object, java.lang.String, java.lang.Object[])
15926      * @since 1.6.0
15927      */
15928     public static List<MetaMethod> respondsTo(Object self, String name, Object[] argTypes) {
15929         return InvokerHelper.getMetaClass(self).respondsTo(self, name, argTypes);
15930     }
15931 
15932     /**
15933      * <p>Returns an object satisfying Groovy truth if the implementing MetaClass responds to
15934      * a method with the given name regardless of the arguments.
15935      *
15936      * <p>Note that this method's return value is based on realised methods and does not take into account
15937      * objects or classes that implement invokeMethod or methodMissing
15938      *
15939      * <p>This method is "safe" in that it will always return a value and never throw an exception
15940      *
15941      * @param self The object to inspect
15942      * @param name The name of the method of interest
15943      * @return A List of MetaMethods matching the given name or an empty list if no matching methods exist
15944      * @see groovy.lang.MetaObjectProtocol#respondsTo(java.lang.Object, java.lang.String)
15945      * @since 1.6.1
15946      */
15947     public static List<MetaMethod> respondsTo(Object self, String name) {
15948         return InvokerHelper.getMetaClass(self).respondsTo(self, name);
15949     }
15950 
15951     /**
15952      * <p>Returns true of the implementing MetaClass has a property of the given name
15953      *
15954      * <p>Note that this method will only return true for realised properties and does not take into
15955      * account implementation of getProperty or propertyMissing
15956      *
15957      * @param self The object to inspect
15958      * @param name The name of the property of interest
15959      * @return The found MetaProperty or null if it doesn't exist
15960      * @see groovy.lang.MetaObjectProtocol#hasProperty(java.lang.Object, java.lang.String)
15961      * @since 1.6.1
15962      */
15963     public static MetaProperty hasProperty(Object self, String name) {
15964         return InvokerHelper.getMetaClass(self).hasProperty(self, name);
15965     }
15966 
15967     @Deprecated
15968     public static boolean asBoolean(CharSequence string) {
15969         return StringGroovyMethods.asBoolean(string);
15970     }
15971 
15972     @Deprecated
15973     public static boolean asBoolean(Matcher matcher) {
15974         return StringGroovyMethods.asBoolean(matcher);
15975     }
15976 
15977     @Deprecated
15978     public static <T> T asType(CharSequence self, Class<T> c) {
15979         return StringGroovyMethods.asType(self, c);
15980     }
15981 
15982     @Deprecated
15983     @SuppressWarnings("unchecked")
15984     public static <T> T asType(GString self, Class<T> c) {
15985         return StringGroovyMethods.asType(self, c);
15986     }
15987 
15988     @Deprecated
15989     @SuppressWarnings("unchecked")
15990     public static <T> T asType(String self, Class<T> c) {
15991         return StringGroovyMethods.asType(self, c);
15992     }
15993 
15994     @Deprecated
15995     public static Pattern bitwiseNegate(CharSequence self) {
15996         return StringGroovyMethods.bitwiseNegate(self);
15997     }
15998 
15999     @Deprecated
16000     public static Pattern bitwiseNegate(String self) {
16001         return StringGroovyMethods.bitwiseNegate(self);
16002     }
16003 
16004     @Deprecated
16005     public static CharSequence capitalize(CharSequence self) {
16006         return StringGroovyMethods.capitalize(self);
16007     }
16008 
16009     @Deprecated
16010     public static String capitalize(String self) {
16011         return StringGroovyMethods.capitalize(self);
16012     }
16013 
16014     @Deprecated
16015     public static CharSequence center(CharSequence self, Number numberOfChars) {
16016         return StringGroovyMethods.center(self, numberOfChars);
16017     }
16018 
16019     @Deprecated
16020     public static CharSequence center(CharSequence self, Number numberOfChars, CharSequence padding) {
16021         return StringGroovyMethods.center(self, numberOfChars, padding);
16022     }
16023 
16024     @Deprecated
16025     public static String center(String self, Number numberOfChars) {
16026         return StringGroovyMethods.center(self, numberOfChars);
16027     }
16028 
16029     @Deprecated
16030     public static String center(String self, Number numberOfChars, String padding) {
16031         return StringGroovyMethods.center(self, numberOfChars, padding);
16032     }
16033 
16034     @Deprecated
16035     public static boolean contains(CharSequence self, CharSequence text) {
16036         return StringGroovyMethods.contains(self, text);
16037     }
16038 
16039     @Deprecated
16040     public static boolean contains(String self, String text) {
16041         return StringGroovyMethods.contains(self, text);
16042     }
16043 
16044     @Deprecated
16045     public static int count(CharSequence self, CharSequence text) {
16046         return StringGroovyMethods.count(self, text);
16047     }
16048 
16049     @Deprecated
16050     public static int count(String self, String text) {
16051         return StringGroovyMethods.count(self, text);
16052     }
16053 
16054     @Deprecated
16055     protected static StringBufferWriter createStringBufferWriter(StringBuffer self) {
16056         return new StringBufferWriter(self);
16057     }
16058 
16059     @Deprecated
16060     protected static StringWriter createStringWriter(String self) {
16061         StringWriter answer = new StringWriter();
16062         answer.write(self);
16063         return answer;
16064     }
16065 
16066     @Deprecated
16067     public static CharSequence denormalize(final CharSequence self) {
16068         return StringGroovyMethods.denormalize(self);
16069     }
16070 
16071     @Deprecated
16072     public static String denormalize(final String self) {
16073         return StringGroovyMethods.denormalize(self);
16074     }
16075 
16076     @Deprecated
16077     public static CharSequence
16078     drop(CharSequence self, int num) {
16079         return StringGroovyMethods.drop(self, num);
16080     }
16081 
16082     @Deprecated
16083     public static <T> T eachLine(CharSequence self, Closure<T> closure) throws IOException {
16084         return StringGroovyMethods.eachLine(self, closure);
16085     }
16086 
16087     @Deprecated
16088     public static <T> T eachLine(CharSequence self, int firstLine, Closure<T> closure) throws IOException {
16089         return StringGroovyMethods.eachLine(self, firstLine, closure);
16090     }
16091 
16092     @Deprecated
16093     public static <T> T eachLine(String self, Closure<T> closure) throws IOException {
16094         return StringGroovyMethods.eachLine(self, closure);
16095     }
16096 
16097     @Deprecated
16098     public static <T> T eachLine(String self, int firstLine, Closure<T> closure) throws IOException {
16099         return StringGroovyMethods.eachLine(self, firstLine, closure);
16100     }
16101 
16102     @Deprecated
16103     public static String eachMatch(CharSequence self, CharSequence regex, Closure closure) {
16104         return (String) StringGroovyMethods.eachMatch(self, regex, closure);
16105     }
16106 
16107     @Deprecated
16108     public static String eachMatch(CharSequence self, Pattern pattern, Closure closure) {
16109         return (String) StringGroovyMethods.eachMatch(self, pattern, closure);
16110     }
16111 
16112     @Deprecated
16113     public static String eachMatch(String self, Pattern pattern, Closure closure) {
16114         return StringGroovyMethods.eachMatch(self, pattern, closure);
16115     }
16116 
16117     @Deprecated
16118     public static String eachMatch(String self, String regex, Closure closure) {
16119         return StringGroovyMethods.eachMatch(self, regex, closure);
16120     }
16121 
16122     @Deprecated
16123     public static CharSequence expand(CharSequence self) {
16124         return StringGroovyMethods.expand(self);
16125     }
16126 
16127     @Deprecated
16128     public static CharSequence expand(CharSequence self, int tabStop) {
16129         return StringGroovyMethods.expand(self, tabStop);
16130     }
16131 
16132     @Deprecated
16133     public static String expand(String self) {
16134         return StringGroovyMethods.expand(self);
16135     }
16136 
16137     @Deprecated
16138     public static String expand(String self, int tabStop) {
16139         return StringGroovyMethods.expand(self, tabStop);
16140     }
16141 
16142     @Deprecated
16143     public static CharSequence expandLine(CharSequence self, int tabStop) {
16144         return StringGroovyMethods.expandLine(self, tabStop);
16145     }
16146 
16147     @Deprecated
16148     public static String expandLine(String self, int tabStop) {
16149         return StringGroovyMethods.expandLine(self, tabStop);
16150     }
16151 
16152     @Deprecated
16153     public static CharSequence find(CharSequence self, CharSequence regex) {
16154         return StringGroovyMethods.find(self, regex);
16155     }
16156 
16157     @Deprecated
16158     public static CharSequence find(CharSequence self, CharSequence regex, Closure closure) {
16159         return StringGroovyMethods.find(self, regex, closure);
16160     }
16161 
16162     @Deprecated
16163     public static CharSequence find(CharSequence self, Pattern pattern) {
16164         return StringGroovyMethods.find(self, pattern);
16165     }
16166 
16167     @Deprecated
16168     public static CharSequence find(CharSequence self, Pattern pattern, Closure closure) {
16169         return StringGroovyMethods.find(self, pattern, closure);
16170     }
16171 
16172     @Deprecated
16173     public static String find(String self, Pattern pattern) {
16174         return StringGroovyMethods.find(self, pattern);
16175     }
16176 
16177     @Deprecated
16178     public static String find(String self, Pattern pattern, Closure closure) {
16179         return StringGroovyMethods.find(self, pattern, closure);
16180     }
16181 
16182     @Deprecated
16183     public static String find(String self, String regex) {
16184         return StringGroovyMethods.find(self, regex);
16185     }
16186 
16187     @Deprecated
16188     public static String find(String self, String regex, Closure closure) {
16189         return StringGroovyMethods.find(self, regex, closure);
16190     }
16191 
16192     @Deprecated
16193     public static List<String> findAll(CharSequence self, CharSequence regex) {
16194         return StringGroovyMethods.findAll(self, regex);
16195     }
16196 
16197     @Deprecated
16198     public static <T> List<T> findAll(CharSequence self, CharSequence regex, Closure<T> closure) {
16199         return StringGroovyMethods.findAll(self, regex, closure);
16200     }
16201 
16202     @Deprecated
16203     public static List<String> findAll(CharSequence self, Pattern pattern) {
16204         return StringGroovyMethods.findAll(self, pattern);
16205     }
16206 
16207     @Deprecated
16208     public static <T> List<T> findAll(CharSequence self, Pattern pattern, Closure<T> closure) {
16209         return StringGroovyMethods.findAll(self, pattern, closure);
16210     }
16211 
16212     @Deprecated
16213     public static List<String> findAll(String self, Pattern pattern) {
16214         return StringGroovyMethods.findAll(self, pattern);
16215     }
16216 
16217     @Deprecated
16218     public static <T> List<T> findAll(String self, Pattern pattern, Closure<T> closure) {
16219         return StringGroovyMethods.findAll(self, pattern, closure);
16220     }
16221 
16222     @Deprecated
16223     public static List<String> findAll(String self, String regex) {
16224         return StringGroovyMethods.findAll(self, regex);
16225     }
16226 
16227     @Deprecated
16228     public static <T> List<T> findAll(String self, String regex, Closure<T> closure) {
16229         return StringGroovyMethods.findAll(self, regex, closure);
16230     }
16231 
16232     @Deprecated
16233     public static CharSequence getAt(CharSequence self, Collection indices) {
16234         return StringGroovyMethods.getAt(self, indices);
16235     }
16236 
16237     @Deprecated
16238     public static CharSequence getAt(CharSequence text, EmptyRange range) {
16239         return StringGroovyMethods.getAt(text, range);
16240     }
16241 
16242     @Deprecated
16243     public static CharSequence getAt(CharSequence text, int index) {
16244         return StringGroovyMethods.getAt(text, index);
16245     }
16246 
16247     @Deprecated
16248     public static CharSequence getAt(CharSequence text, IntRange range) {
16249         return StringGroovyMethods.getAt(text, range);
16250     }
16251 
16252     @Deprecated
16253     public static CharSequence getAt(CharSequence text, Range range) {
16254         return StringGroovyMethods.getAt(text, range);
16255     }
16256 
16257     @Deprecated
16258     public static List getAt(Matcher self, Collection indices) {
16259         return StringGroovyMethods.getAt(self, indices);
16260     }
16261 
16262     @Deprecated
16263     public static Object getAt(Matcher matcher, int idx) {
16264         return StringGroovyMethods.getAt(matcher, idx);
16265     }
16266 
16267     @Deprecated
16268     public static String getAt(String self, Collection indices) {
16269         return StringGroovyMethods.getAt(self, indices);
16270     }
16271 
16272     @Deprecated
16273     public static String getAt(String text, EmptyRange range) {
16274         return StringGroovyMethods.getAt(text, range);
16275     }
16276 
16277     @Deprecated
16278     public static String getAt(String text, int index) {
16279         return StringGroovyMethods.getAt(text, index);
16280     }
16281 
16282     @Deprecated
16283     public static String getAt(String text, IntRange range) {
16284         return StringGroovyMethods.getAt(text, range);
16285     }
16286 
16287     @Deprecated
16288     public static String getAt(String text, Range range) {
16289         return StringGroovyMethods.getAt(text, range);
16290     }
16291 
16292     @Deprecated
16293     public static char[] getChars(CharSequence self) {
16294         return StringGroovyMethods.getChars(self);
16295     }
16296 
16297     @Deprecated
16298     public static char[] getChars(String self) {
16299         return StringGroovyMethods.getChars(self);
16300     }
16301 
16302     @Deprecated
16303     public static int getCount(Matcher matcher) {
16304         return StringGroovyMethods.getCount(matcher);
16305     }
16306 
16307     @Deprecated
16308     public static boolean hasGroup(Matcher matcher) {
16309         return StringGroovyMethods.hasGroup(matcher);
16310     }
16311 
16312     @Deprecated
16313     public static boolean isAllWhitespace(CharSequence self) {
16314         return StringGroovyMethods.isAllWhitespace(self);
16315     }
16316 
16317     @Deprecated
16318     public static boolean isAllWhitespace(String self) {
16319         return StringGroovyMethods.isAllWhitespace(self);
16320     }
16321 
16322     @Deprecated
16323     public static boolean isBigDecimal(CharSequence self) {
16324         return StringGroovyMethods.isBigDecimal(self);
16325     }
16326 
16327     @Deprecated
16328     public static boolean isBigDecimal(String self) {
16329         return StringGroovyMethods.isBigDecimal(self);
16330     }
16331 
16332     @Deprecated
16333     public static boolean isBigInteger(CharSequence self) {
16334         return StringGroovyMethods.isBigInteger(self);
16335     }
16336 
16337     @Deprecated
16338     public static boolean isBigInteger(String self) {
16339         return StringGroovyMethods.isBigInteger(self);
16340     }
16341 
16342     @Deprecated
16343     public static boolean isCase(CharSequence caseValue, Object switchValue) {
16344         return StringGroovyMethods.isCase(caseValue, switchValue);
16345     }
16346 
16347     @Deprecated
16348     public static boolean isCase(GString caseValue, Object switchValue) {
16349         return StringGroovyMethods.isCase(caseValue, switchValue);
16350     }
16351 
16352     @Deprecated
16353     public static boolean isCase(Pattern caseValue, Object switchValue) {
16354         return StringGroovyMethods.isCase(caseValue, switchValue);
16355     }
16356 
16357     @Deprecated
16358     public static boolean isCase(String caseValue, Object switchValue) {
16359         return StringGroovyMethods.isCase(caseValue, switchValue);
16360     }
16361 
16362     @Deprecated
16363     public static boolean isDouble(CharSequence self) {
16364         return StringGroovyMethods.isDouble(self);
16365     }
16366 
16367     @Deprecated
16368     public static boolean isDouble(String self) {
16369         return StringGroovyMethods.isDouble(self);
16370     }
16371 
16372     @Deprecated
16373     public static boolean isFloat(CharSequence self) {
16374         return StringGroovyMethods.isFloat(self);
16375     }
16376 
16377     @Deprecated
16378     public static boolean isFloat(String self) {
16379         return StringGroovyMethods.isFloat(self);
16380     }
16381 
16382     @Deprecated
16383     public static boolean isInteger(CharSequence self) {
16384         return StringGroovyMethods.isInteger(self);
16385     }
16386 
16387     @Deprecated
16388     public static boolean isInteger(String self) {
16389         return StringGroovyMethods.isInteger(self);
16390     }
16391 
16392     @Deprecated
16393     public static boolean isLong(CharSequence self) {
16394         return StringGroovyMethods.isLong(self);
16395     }
16396 
16397     @Deprecated
16398     public static boolean isLong(String self) {
16399         return StringGroovyMethods.isLong(self);
16400     }
16401 
16402     @Deprecated
16403     public static boolean isNumber(CharSequence self) {
16404         return StringGroovyMethods.isNumber(self);
16405     }
16406 
16407     @Deprecated
16408     public static boolean isNumber(String self) {
16409         return StringGroovyMethods.isNumber(self);
16410     }
16411 
16412     @Deprecated
16413     public static Iterator iterator(final Matcher matcher) {
16414         return StringGroovyMethods.iterator(matcher);
16415     }
16416 
16417     @Deprecated
16418     public static StringBuilder leftShift(CharSequence self, Object value) {
16419         return StringGroovyMethods.leftShift(self, value);
16420     }
16421 
16422     @Deprecated
16423     public static StringBuffer leftShift(String self, Object value) {
16424         return StringGroovyMethods.leftShift(self, value);
16425     }
16426 
16427     @Deprecated
16428     public static StringBuffer leftShift(StringBuffer self, Object value) {
16429         return StringGroovyMethods.leftShift(self, value);
16430     }
16431 
16432     @Deprecated
16433     public static StringBuilder leftShift(StringBuilder self, Object value) {
16434         return StringGroovyMethods.leftShift(self, value);
16435     }
16436 
16437     @Deprecated
16438     public static boolean matches(CharSequence self, Pattern pattern) {
16439         return StringGroovyMethods.matches(self, pattern);
16440     }
16441 
16442     @Deprecated
16443     public static boolean matches(String self, Pattern pattern) {
16444         return StringGroovyMethods.matches(self, pattern);
16445     }
16446 
16447     @Deprecated
16448     public static CharSequence minus(CharSequence self, Object target) {
16449         return StringGroovyMethods.minus(self, target);
16450     }
16451 
16452     @Deprecated
16453     public static String minus(String self, Object target) {
16454         return StringGroovyMethods.minus(self, target);
16455     }
16456 
16457     @Deprecated
16458     public static CharSequence multiply(CharSequence self, Number factor) {
16459         return StringGroovyMethods.multiply(self, factor);
16460     }
16461 
16462     @Deprecated
16463     public static String multiply(String self, Number factor) {
16464         return StringGroovyMethods.multiply(self, factor);
16465     }
16466 
16467     @Deprecated
16468     public static CharSequence next(CharSequence self) {
16469         return StringGroovyMethods.next(self);
16470     }
16471 
16472     @Deprecated
16473     public static String next(String self) {
16474         return StringGroovyMethods.next(self);
16475     }
16476 
16477     @Deprecated
16478     public static CharSequence normalize(final CharSequence self) {
16479         return StringGroovyMethods.normalize(self);
16480     }
16481 
16482     @Deprecated
16483     public static String normalize(final String self) {
16484         return StringGroovyMethods.normalize(self);
16485     }
16486 
16487     @Deprecated
16488     public static CharSequence padLeft(CharSequence self, Number numberOfChars) {
16489         return StringGroovyMethods.padLeft(self, numberOfChars);
16490     }
16491 
16492     @Deprecated
16493     public static CharSequence padLeft(CharSequence self, Number numberOfChars, CharSequence padding) {
16494         return StringGroovyMethods.padLeft(self, numberOfChars, padding);
16495     }
16496 
16497     @Deprecated
16498     public static String padLeft(String self, Number numberOfChars) {
16499         return StringGroovyMethods.padLeft(self, numberOfChars);
16500     }
16501 
16502     @Deprecated
16503     public static String padLeft(String self, Number numberOfChars, String padding) {
16504         return StringGroovyMethods.padLeft(self, numberOfChars, padding);
16505     }
16506 
16507     @Deprecated
16508     public static CharSequence padRight(CharSequence self, Number numberOfChars) {
16509         return StringGroovyMethods.padRight(self, numberOfChars);
16510     }
16511 
16512     @Deprecated
16513     public static CharSequence padRight(CharSequence self, Number numberOfChars, CharSequence padding) {
16514         return StringGroovyMethods.padRight(self, numberOfChars, padding);
16515     }
16516 
16517     @Deprecated
16518     public static String padRight(String self, Number numberOfChars) {
16519         return StringGroovyMethods.padRight(self, numberOfChars);
16520     }
16521 
16522     @Deprecated
16523     public static String padRight(String self, Number numberOfChars, String padding) {
16524         return StringGroovyMethods.padRight(self, numberOfChars, padding);
16525     }
16526 
16527     @Deprecated
16528     public static CharSequence plus(CharSequence left, Object value) {
16529         return StringGroovyMethods.plus(left, value);
16530     }
16531 
16532     @Deprecated
16533     public static String plus(Number value, String right) {
16534         return StringGroovyMethods.plus(value, right);
16535     }
16536 
16537     @Deprecated
16538     public static String plus(String left, Object value) {
16539         return StringGroovyMethods.plus(left, value);
16540     }
16541 
16542     @Deprecated
16543     public static String plus(StringBuffer left, String value) {
16544         return StringGroovyMethods.plus(left, value);
16545     }
16546 
16547     @Deprecated
16548     public static CharSequence previous(CharSequence self) {
16549         return StringGroovyMethods.previous(self);
16550     }
16551 
16552     @Deprecated
16553     public static String previous(String self) {
16554         return StringGroovyMethods.previous(self);
16555     }
16556 
16557     @Deprecated
16558     public static void putAt(StringBuffer self, EmptyRange range, Object value) {
16559         StringGroovyMethods.putAt(self, range, value);
16560     }
16561 
16562     @Deprecated
16563     public static void putAt(StringBuffer self, IntRange range, Object value) {
16564         StringGroovyMethods.putAt(self, range, value);
16565     }
16566 
16567     @Deprecated
16568     public static List<String> readLines(CharSequence self) throws IOException {
16569         return StringGroovyMethods.readLines(self);
16570     }
16571 
16572     @Deprecated
16573     public static List<String> readLines(String self) throws IOException {
16574         return StringGroovyMethods.readLines(self);
16575     }
16576 
16577     @Deprecated
16578     public static CharSequence replaceAll(final CharSequence self, final CharSequence regex, final CharSequence replacement) {
16579         return StringGroovyMethods.replaceAll(self, regex, replacement);
16580     }
16581 
16582     @Deprecated
16583     public static CharSequence replaceAll(final CharSequence self, final CharSequence regex, final Closure closure) {
16584         return StringGroovyMethods.replaceAll(self, regex, closure);
16585     }
16586 
16587     @Deprecated
16588     public static CharSequence replaceAll(CharSequence self, Pattern pattern, CharSequence replacement) {
16589         return StringGroovyMethods.replaceAll(self, pattern, replacement);
16590     }
16591 
16592     @Deprecated
16593     public static String replaceAll(final CharSequence self, final Pattern pattern, final Closure closure) {
16594         return StringGroovyMethods.replaceAll(self, pattern, closure);
16595     }
16596 
16597     @Deprecated
16598     public static String replaceAll(final String self, final Pattern pattern, final Closure closure) {
16599         return StringGroovyMethods.replaceAll(self, pattern, closure);
16600     }
16601 
16602     @Deprecated
16603     public static String replaceAll(String self, Pattern pattern, String replacement) {
16604         return StringGroovyMethods.replaceAll(self, pattern, replacement);
16605     }
16606 
16607     @Deprecated
16608     public static String replaceAll(final String self, final String regex, final Closure closure) {
16609         return StringGroovyMethods.replaceAll(self, regex, closure);
16610     }
16611 
16612     @Deprecated
16613     public static String replaceFirst(final CharSequence self, final CharSequence regex, final CharSequence replacement) {
16614         return StringGroovyMethods.replaceFirst(self, regex, replacement);
16615     }
16616 
16617     @Deprecated
16618     public static String replaceFirst(final CharSequence self, final CharSequence regex, final Closure closure) {
16619         return StringGroovyMethods.replaceFirst(self, regex, closure);
16620     }
16621 
16622     @Deprecated
16623     public static CharSequence replaceFirst(CharSequence self, Pattern pattern, CharSequence replacement) {
16624         return StringGroovyMethods.replaceFirst(self, pattern, replacement);
16625     }
16626 
16627     @Deprecated
16628     public static String replaceFirst(final CharSequence self, final Pattern pattern, final Closure closure) {
16629         return StringGroovyMethods.replaceFirst(self, pattern, closure);
16630     }
16631 
16632     @Deprecated
16633     public static String replaceFirst(final String self, final Pattern pattern, final Closure closure) {
16634         return StringGroovyMethods.replaceFirst(self, pattern, closure);
16635     }
16636 
16637     @Deprecated
16638     public static String replaceFirst(String self, Pattern pattern, String replacement) {
16639         return StringGroovyMethods.replaceFirst(self, pattern, replacement);
16640     }
16641 
16642     @Deprecated
16643     public static String replaceFirst(final String self, final String regex, final Closure closure) {
16644         return StringGroovyMethods.replaceFirst(self, regex, closure);
16645     }
16646 
16647     @Deprecated
16648     public static CharSequence reverse(CharSequence self) {
16649         return StringGroovyMethods.reverse(self);
16650     }
16651 
16652     @Deprecated
16653     public static String reverse(String self) {
16654         return StringGroovyMethods.reverse(self);
16655     }
16656 
16657     @Deprecated
16658     public static void setIndex(Matcher matcher, int idx) {
16659         StringGroovyMethods.setIndex(matcher, idx);
16660     }
16661 
16662     @Deprecated
16663     public static int size(CharSequence text) {
16664         return StringGroovyMethods.size(text);
16665     }
16666 
16667     @Deprecated
16668     public static long size(Matcher self) {
16669         return StringGroovyMethods.size(self);
16670     }
16671 
16672     @Deprecated
16673     public static int size(String text) {
16674         return StringGroovyMethods.size(text);
16675     }
16676 
16677     @Deprecated
16678     public static int size(StringBuffer buffer) {
16679         return StringGroovyMethods.size(buffer);
16680     }
16681 
16682     @Deprecated
16683     public static CharSequence[] split(CharSequence self) {
16684         return StringGroovyMethods.split(self);
16685     }
16686 
16687     @Deprecated
16688     public static String[] split(GString self) {
16689         return StringGroovyMethods.split(self);
16690     }
16691 
16692     @Deprecated
16693     public static String[] split(String self) {
16694         return StringGroovyMethods.split(self);
16695     }
16696 
16697     @Deprecated
16698     public static <T> T splitEachLine(CharSequence self, CharSequence regex, Closure<T> closure) throws IOException {
16699         return StringGroovyMethods.splitEachLine(self, regex, closure);
16700     }
16701 
16702     @Deprecated
16703     public static <T> T splitEachLine(CharSequence self, Pattern pattern, Closure<T> closure) throws IOException {
16704         return StringGroovyMethods.splitEachLine(self, pattern, closure);
16705     }
16706 
16707     @Deprecated
16708     public static <T> T splitEachLine(String self, Pattern pattern, Closure<T> closure) throws IOException {
16709         return StringGroovyMethods.splitEachLine(self, pattern, closure);
16710     }
16711 
16712     @Deprecated
16713     public static <T> T splitEachLine(String self, String regex, Closure<T> closure) throws IOException {
16714         return StringGroovyMethods.splitEachLine(self, regex, closure);
16715     }
16716 
16717     @Deprecated
16718     public static CharSequence stripIndent(CharSequence self) {
16719         return StringGroovyMethods.stripIndent(self);
16720     }
16721 
16722     @Deprecated
16723     public static CharSequence stripIndent(CharSequence self, int numChars) {
16724         return StringGroovyMethods.stripIndent(self, numChars);
16725     }
16726 
16727     @Deprecated
16728     public static String stripIndent(String self) {
16729         return StringGroovyMethods.stripIndent(self);
16730     }
16731 
16732     @Deprecated
16733     public static String stripIndent(String self, int numChars) {
16734         return StringGroovyMethods.stripIndent(self, numChars);
16735     }
16736 
16737     @Deprecated
16738     public static CharSequence stripMargin(CharSequence self) {
16739         return StringGroovyMethods.stripMargin(self);
16740     }
16741 
16742     @Deprecated
16743     public static CharSequence stripMargin(CharSequence self, char marginChar) {
16744         return StringGroovyMethods.stripMargin(self, marginChar);
16745     }
16746 
16747     @Deprecated
16748     public static String stripMargin(CharSequence self, CharSequence marginChar) {
16749         return StringGroovyMethods.stripMargin(self, marginChar);
16750     }
16751 
16752     @Deprecated
16753     public static String stripMargin(String self) {
16754         return StringGroovyMethods.stripMargin(self);
16755     }
16756 
16757     @Deprecated
16758     public static String stripMargin(String self, char marginChar) {
16759         return StringGroovyMethods.stripMargin(self, marginChar);
16760     }
16761 
16762     @Deprecated
16763     public static String stripMargin(String self, String marginChar) {
16764         return StringGroovyMethods.stripMargin(self, marginChar);
16765     }
16766 
16767     @Deprecated
16768     public static BigDecimal toBigDecimal(CharSequence self) {
16769         return StringGroovyMethods.toBigDecimal(self);
16770     }
16771 
16772     @Deprecated
16773     public static BigDecimal toBigDecimal(String self) {
16774         return StringGroovyMethods.toBigDecimal(self);
16775     }
16776 
16777     @Deprecated
16778     public static BigInteger toBigInteger(CharSequence self) {
16779         return StringGroovyMethods.toBigInteger(self);
16780     }
16781 
16782     @Deprecated
16783     public static BigInteger toBigInteger(String self) {
16784         return StringGroovyMethods.toBigInteger(self);
16785     }
16786 
16787     @Deprecated
16788     public static Boolean toBoolean(String self) {
16789         return StringGroovyMethods.toBoolean(self);
16790     }
16791 
16792     @Deprecated
16793     public static Character toCharacter(String self) {
16794         return StringGroovyMethods.toCharacter(self);
16795     }
16796 
16797     @Deprecated
16798     public static Double toDouble(CharSequence self) {
16799         return StringGroovyMethods.toDouble(self);
16800     }
16801 
16802     @Deprecated
16803     public static Double toDouble(String self) {
16804         return StringGroovyMethods.toDouble(self);
16805     }
16806 
16807     @Deprecated
16808     public static Float toFloat(CharSequence self) {
16809         return StringGroovyMethods.toFloat(self);
16810     }
16811 
16812     @Deprecated
16813     public static Float toFloat(String self) {
16814         return StringGroovyMethods.toFloat(self);
16815     }
16816 
16817     @Deprecated
16818     public static Integer toInteger(CharSequence self) {
16819         return StringGroovyMethods.toInteger(self);
16820     }
16821 
16822     @Deprecated
16823     public static Integer toInteger(String self) {
16824         return StringGroovyMethods.toInteger(self);
16825     }
16826 
16827     @Deprecated
16828     public static List<String> tokenize(CharSequence self) {
16829         return StringGroovyMethods.tokenize(self);
16830     }
16831 
16832     @Deprecated
16833     public static List<String> tokenize(CharSequence self, Character token) {
16834         return StringGroovyMethods.tokenize(self, token);
16835     }
16836 
16837     @Deprecated
16838     public static List<String> tokenize(CharSequence self, CharSequence token) {
16839         return StringGroovyMethods.tokenize(self, token);
16840     }
16841 
16842     @Deprecated
16843     @SuppressWarnings("unchecked")
16844     public static List<String> tokenize(String self) {
16845         return StringGroovyMethods.tokenize(self);
16846     }
16847 
16848     @Deprecated
16849     public static List<String> tokenize(String self, Character token) {
16850         return StringGroovyMethods.tokenize(self, token);
16851     }
16852 
16853     @Deprecated
16854     @SuppressWarnings("unchecked")
16855     public static List<String> tokenize(String self, String token) {
16856         return StringGroovyMethods.tokenize(self, token);
16857     }
16858 
16859     @Deprecated
16860     public static List<String> toList(CharSequence self) {
16861         return StringGroovyMethods.toList(self);
16862     }
16863 
16864     @Deprecated
16865     public static List<String> toList(String self) {
16866         return StringGroovyMethods.toList(self);
16867     }
16868 
16869     @Deprecated
16870     public static Long toLong(CharSequence self) {
16871         return StringGroovyMethods.toLong(self);
16872     }
16873 
16874     @Deprecated
16875     public static Long toLong(String self) {
16876         return StringGroovyMethods.toLong(self);
16877     }
16878 
16879     @Deprecated
16880     public static Set<String> toSet(CharSequence self) {
16881         return StringGroovyMethods.toSet(self);
16882     }
16883 
16884     @Deprecated
16885     public static Set<String> toSet(String self) {
16886         return StringGroovyMethods.toSet(self);
16887     }
16888 
16889     @Deprecated
16890     public static Short toShort(CharSequence self) {
16891         return StringGroovyMethods.toShort(self);
16892     }
16893 
16894     @Deprecated
16895     public static Short toShort(String self) {
16896         return StringGroovyMethods.toShort(self);
16897     }
16898 
16899     @Deprecated
16900     public static URI toURI(CharSequence self) throws URISyntaxException {
16901         return ResourceGroovyMethods.toURI(self);
16902     }
16903 
16904     @Deprecated
16905     public static URI toURI(String self) throws URISyntaxException {
16906         return ResourceGroovyMethods.toURI(self);
16907     }
16908 
16909     @Deprecated
16910     public static URL toURL(CharSequence self) throws MalformedURLException {
16911         return ResourceGroovyMethods.toURL(self);
16912     }
16913 
16914     @Deprecated
16915     public static URL toURL(String self) throws MalformedURLException {
16916         return ResourceGroovyMethods.toURL(self);
16917     }
16918 
16919     @Deprecated
16920     public static CharSequence tr(final CharSequence self, CharSequence sourceSet, CharSequence replacementSet) throws ClassNotFoundException {
16921         return StringGroovyMethods.tr(self, sourceSet, replacementSet);
16922     }
16923 
16924     @Deprecated
16925     public static String tr(final String self, String sourceSet, String replacementSet) throws ClassNotFoundException {
16926         return StringGroovyMethods.tr(self, sourceSet, replacementSet);
16927     }
16928 
16929     @Deprecated
16930     public static CharSequence unexpand(CharSequence self) {
16931         return StringGroovyMethods.unexpand(self);
16932     }
16933 
16934     @Deprecated
16935     public static CharSequence unexpand(CharSequence self, int tabStop) {
16936         return StringGroovyMethods.unexpand(self, tabStop);
16937     }
16938 
16939     @Deprecated
16940     public static String unexpand(String self) {
16941         return StringGroovyMethods.unexpand(self);
16942     }
16943 
16944     @Deprecated
16945     public static String unexpand(String self, int tabStop) {
16946         return StringGroovyMethods.unexpand(self, tabStop);
16947     }
16948 
16949     @Deprecated
16950     public static CharSequence unexpandLine(CharSequence self, int tabStop) {
16951         return StringGroovyMethods.unexpandLine(self, tabStop);
16952     }
16953 
16954     @Deprecated
16955     public static String unexpandLine(String self, int tabStop) {
16956         return StringGroovyMethods.unexpandLine(self, tabStop);
16957     }
16958 
16959     @Deprecated
16960     public static Process execute(final String self) throws IOException {
16961         return ProcessGroovyMethods.execute(self);
16962     }
16963 
16964     @Deprecated
16965     public static Process execute(final String self, final String[] envp, final File dir) throws IOException {
16966         return ProcessGroovyMethods.execute(self, envp, dir);
16967     }
16968 
16969     @Deprecated
16970     public static Process execute(final String self, final List envp, final File dir) throws IOException {
16971         return ProcessGroovyMethods.execute(self, envp, dir);
16972     }
16973 
16974     @Deprecated
16975     public static Process execute(final String[] commandArray) throws IOException {
16976         return ProcessGroovyMethods.execute(commandArray);
16977     }
16978 
16979     @Deprecated
16980     public static Process execute(final String[] commandArray, final String[] envp, final File dir) throws IOException {
16981         return ProcessGroovyMethods.execute(commandArray, envp, dir);
16982     }
16983 
16984     @Deprecated
16985     public static Process execute(final String[] commandArray, final List envp, final File dir) throws IOException {
16986         return ProcessGroovyMethods.execute(commandArray, envp, dir);
16987     }
16988 
16989     @Deprecated
16990     public static Process execute(final List commands) throws IOException {
16991         return ProcessGroovyMethods.execute(commands);
16992     }
16993 
16994     @Deprecated
16995     public static Process execute(final List commands, final String[] envp, final File dir) throws IOException {
16996         return ProcessGroovyMethods.execute(commands, envp, dir);
16997     }
16998 
16999     @Deprecated
17000     public static Process execute(final List commands, final List envp, final File dir) throws IOException {
17001         return ProcessGroovyMethods.execute(commands, envp, dir);
17002     }
17003 
17004     @Deprecated
17005     public static <T> T withStreams(Socket socket, Closure<T> closure) throws IOException {
17006         return SocketGroovyMethods.withStreams(socket, closure);
17007     }
17008 
17009     @Deprecated
17010     public static <T> T withObjectStreams(Socket socket, Closure<T> closure) throws IOException {
17011         return SocketGroovyMethods.withObjectStreams(socket, closure);
17012     }
17013 
17014     @Deprecated
17015     public static Writer leftShift(Socket self, Object value) throws IOException {
17016         return SocketGroovyMethods.leftShift(self, value);
17017     }
17018 
17019     @Deprecated
17020     public static OutputStream leftShift(Socket self, byte[] value) throws IOException {
17021         return SocketGroovyMethods.leftShift(self, value);
17022     }
17023 
17024     @Deprecated
17025     public static Socket accept(ServerSocket serverSocket, final Closure closure) throws IOException {
17026         return SocketGroovyMethods.accept(serverSocket, closure);
17027     }
17028 
17029     @Deprecated
17030     public static Socket accept(ServerSocket serverSocket, final boolean runInANewThread,
17031                                 final Closure closure) throws IOException {
17032         return SocketGroovyMethods.accept(serverSocket, runInANewThread, closure);
17033     }
17034 
17035     @Deprecated
17036     public static long size(File self) {
17037         return ResourceGroovyMethods.size(self);
17038     }
17039 
17040     @Deprecated
17041     public static Writer leftShift(Writer self, Object value) throws IOException {
17042         return IOGroovyMethods.leftShift(self, value);
17043     }
17044 
17045     @Deprecated
17046     public static void write(Writer self, Writable writable) throws IOException {
17047         IOGroovyMethods.write(self, writable);
17048     }
17049 
17050     @Deprecated
17051     public static Writer leftShift(OutputStream self, Object value) throws IOException {
17052         return IOGroovyMethods.leftShift(self, value);
17053     }
17054 
17055     @Deprecated
17056     public static void leftShift(ObjectOutputStream self, Object value) throws IOException {
17057         IOGroovyMethods.leftShift(self, value);
17058     }
17059 
17060     @Deprecated
17061     public static OutputStream leftShift(OutputStream self, InputStream in) throws IOException {
17062         return IOGroovyMethods.leftShift(self, in);
17063     }
17064 
17065     @Deprecated
17066     public static OutputStream leftShift(OutputStream self, byte[] value) throws IOException {
17067         return IOGroovyMethods.leftShift(self, value);
17068     }
17069 
17070     @Deprecated
17071     public static ObjectOutputStream newObjectOutputStream(File file) throws IOException {
17072         return ResourceGroovyMethods.newObjectOutputStream(file);
17073     }
17074 
17075     @Deprecated
17076     public static ObjectOutputStream newObjectOutputStream(OutputStream outputStream) throws IOException {
17077         return IOGroovyMethods.newObjectOutputStream(outputStream);
17078     }
17079 
17080     @Deprecated
17081     public static <T> T withObjectOutputStream(File file, Closure<T> closure) throws IOException {
17082         return ResourceGroovyMethods.withObjectOutputStream(file, closure);
17083     }
17084 
17085     @Deprecated
17086     public static <T> T withObjectOutputStream(OutputStream outputStream, Closure<T> closure) throws IOException {
17087         return IOGroovyMethods.withObjectOutputStream(outputStream, closure);
17088     }
17089 
17090     @Deprecated
17091     public static ObjectInputStream newObjectInputStream(File file) throws IOException {
17092         return ResourceGroovyMethods.newObjectInputStream(file);
17093     }
17094 
17095     @Deprecated
17096     public static ObjectInputStream newObjectInputStream(InputStream inputStream) throws IOException {
17097         return IOGroovyMethods.newObjectInputStream(inputStream);
17098     }
17099 
17100     @Deprecated
17101     public static ObjectInputStream newObjectInputStream(InputStream inputStream, final ClassLoader classLoader) throws IOException {
17102         return IOGroovyMethods.newObjectInputStream(inputStream, classLoader);
17103     }
17104 
17105     @Deprecated
17106     public static ObjectInputStream newObjectInputStream(File file, final ClassLoader classLoader) throws IOException {
17107         return ResourceGroovyMethods.newObjectInputStream(file, classLoader);
17108     }
17109 
17110     @Deprecated
17111     public static void eachObject(File self, Closure closure) throws IOException, ClassNotFoundException {
17112         ResourceGroovyMethods.eachObject(self, closure);
17113     }
17114 
17115     @Deprecated
17116     public static void eachObject(ObjectInputStream ois, Closure closure) throws IOException, ClassNotFoundException {
17117         IOGroovyMethods.eachObject(ois, closure);
17118     }
17119 
17120     @Deprecated
17121     public static <T> T withObjectInputStream(File file, Closure<T> closure) throws IOException {
17122         return ResourceGroovyMethods.withObjectInputStream(file, closure);
17123     }
17124 
17125     @Deprecated
17126     public static <T> T withObjectInputStream(File file, ClassLoader classLoader, Closure<T> closure) throws IOException {
17127         return ResourceGroovyMethods.withObjectInputStream(file, classLoader, closure);
17128     }
17129 
17130     @Deprecated
17131     public static <T> T withObjectInputStream(InputStream inputStream, Closure<T> closure) throws IOException {
17132         return IOGroovyMethods.withObjectInputStream(inputStream, closure);
17133     }
17134 
17135     @Deprecated
17136     public static <T> T withObjectInputStream(InputStream inputStream, ClassLoader classLoader, Closure<T> closure) throws IOException {
17137         return IOGroovyMethods.withObjectInputStream(inputStream, classLoader, closure);
17138     }
17139 
17140     @Deprecated
17141     public static <T> T eachLine(File self, Closure<T> closure) throws IOException {
17142         return ResourceGroovyMethods.eachLine(self, closure);
17143     }
17144 
17145     @Deprecated
17146     public static <T> T eachLine(File self, String charset, Closure<T> closure) throws IOException {
17147         return ResourceGroovyMethods.eachLine(self, charset, closure);
17148     }
17149 
17150     @Deprecated
17151     public static <T> T eachLine(File self, int firstLine, Closure<T> closure) throws IOException {
17152         return ResourceGroovyMethods.eachLine(self, firstLine, closure);
17153     }
17154 
17155     @Deprecated
17156     public static <T> T eachLine(File self, String charset, int firstLine, Closure<T> closure) throws IOException {
17157         return ResourceGroovyMethods.eachLine(self, charset, firstLine, closure);
17158     }
17159 
17160     @Deprecated
17161     public static <T> T eachLine(InputStream stream, String charset, Closure<T> closure) throws IOException {
17162         return IOGroovyMethods.eachLine(stream, charset, closure);
17163     }
17164 
17165     @Deprecated
17166     public static <T> T eachLine(InputStream stream, String charset, int firstLine, Closure<T> closure) throws IOException {
17167         return IOGroovyMethods.eachLine(stream, charset, firstLine, closure);
17168     }
17169 
17170     @Deprecated
17171     public static <T> T eachLine(InputStream stream, Closure<T> closure) throws IOException {
17172         return IOGroovyMethods.eachLine(stream, closure);
17173     }
17174 
17175     @Deprecated
17176     public static <T> T eachLine(InputStream stream, int firstLine, Closure<T> closure) throws IOException {
17177         return IOGroovyMethods.eachLine(stream, firstLine, closure);
17178     }
17179 
17180     @Deprecated
17181     public static <T> T eachLine(URL url, Closure<T> closure) throws IOException {
17182         return ResourceGroovyMethods.eachLine(url, closure);
17183     }
17184 
17185     @Deprecated
17186     public static <T> T eachLine(URL url, int firstLine, Closure<T> closure) throws IOException {
17187         return ResourceGroovyMethods.eachLine(url, firstLine, closure);
17188     }
17189 
17190     @Deprecated
17191     public static <T> T eachLine(URL url, String charset, Closure<T> closure) throws IOException {
17192         return ResourceGroovyMethods.eachLine(url, charset, closure);
17193     }
17194 
17195     @Deprecated
17196     public static <T> T eachLine(URL url, String charset, int firstLine, Closure<T> closure) throws IOException {
17197         return ResourceGroovyMethods.eachLine(url, charset, firstLine, closure);
17198     }
17199 
17200     @Deprecated
17201     public static <T> T eachLine(Reader self, Closure<T> closure) throws IOException {
17202         return IOGroovyMethods.eachLine(self, closure);
17203     }
17204 
17205     @Deprecated
17206     public static <T> T eachLine(Reader self, int firstLine, Closure<T> closure) throws IOException {
17207         return IOGroovyMethods.eachLine(self, firstLine, closure);
17208     }
17209 
17210     @Deprecated
17211     public static <T> T splitEachLine(File self, String regex, Closure<T> closure) throws IOException {
17212         return ResourceGroovyMethods.splitEachLine(self, regex, closure);
17213     }
17214 
17215     @Deprecated
17216     public static <T> T splitEachLine(File self, Pattern pattern, Closure<T> closure) throws IOException {
17217         return ResourceGroovyMethods.splitEachLine(self, pattern, closure);
17218     }
17219 
17220     @Deprecated
17221     public static <T> T splitEachLine(File self, String regex, String charset, Closure<T> closure) throws IOException {
17222         return ResourceGroovyMethods.splitEachLine(self, regex, charset, closure);
17223     }
17224 
17225     @Deprecated
17226     public static <T> T splitEachLine(File self, Pattern pattern, String charset, Closure<T> closure) throws IOException {
17227         return ResourceGroovyMethods.splitEachLine(self, pattern, charset, closure);
17228     }
17229 
17230     @Deprecated
17231     public static <T> T splitEachLine(URL self, String regex, Closure<T> closure) throws IOException {
17232         return ResourceGroovyMethods.splitEachLine(self, regex, closure);
17233     }
17234 
17235     @Deprecated
17236     public static <T> T splitEachLine(URL self, Pattern pattern, Closure<T> closure) throws IOException {
17237         return ResourceGroovyMethods.splitEachLine(self, pattern, closure);
17238     }
17239 
17240     @Deprecated
17241     public static <T> T splitEachLine(URL self, String regex, String charset, Closure<T> closure) throws IOException {
17242         return ResourceGroovyMethods.splitEachLine(self, regex, charset, closure);
17243     }
17244 
17245     @Deprecated
17246     public static <T> T splitEachLine(URL self, Pattern pattern, String charset, Closure<T> closure) throws IOException {
17247         return ResourceGroovyMethods.splitEachLine(self, pattern, charset, closure);
17248     }
17249 
17250     @Deprecated
17251     public static <T> T splitEachLine(Reader self, String regex, Closure<T> closure) throws IOException {
17252         return IOGroovyMethods.splitEachLine(self, regex, closure);
17253     }
17254 
17255     @Deprecated
17256     public static <T> T splitEachLine(Reader self, Pattern pattern, Closure<T> closure) throws IOException {
17257         return IOGroovyMethods.splitEachLine(self, pattern, closure);
17258     }
17259 
17260     @Deprecated
17261     public static <T> T splitEachLine(InputStream stream, String regex, String charset, Closure<T> closure) throws IOException {
17262         return IOGroovyMethods.splitEachLine(stream, charset, regex, closure);
17263     }
17264 
17265     @Deprecated
17266     public static <T> T splitEachLine(InputStream stream, Pattern pattern, String charset, Closure<T> closure) throws IOException {
17267         return IOGroovyMethods.splitEachLine(stream, pattern, charset, closure);
17268     }
17269 
17270     @Deprecated
17271     public static <T> T splitEachLine(InputStream stream, String regex, Closure<T> closure) throws IOException {
17272         return IOGroovyMethods.splitEachLine(stream, regex, closure);
17273     }
17274 
17275     @Deprecated
17276     public static <T> T splitEachLine(InputStream stream, Pattern pattern, Closure<T> closure) throws IOException {
17277         return IOGroovyMethods.splitEachLine(stream, pattern, closure);
17278     }
17279 
17280     @Deprecated
17281     public static String readLine(Reader self) throws IOException {
17282         return  IOGroovyMethods.readLine(self);
17283     }
17284 
17285     @Deprecated
17286     public static List<String> readLines(File file) throws IOException {
17287         return ResourceGroovyMethods.readLines(file);
17288     }
17289 
17290     @Deprecated
17291     public static List<String> readLines(File file, String charset) throws IOException {
17292         return ResourceGroovyMethods.readLines(file, charset);
17293     }
17294 
17295     @Deprecated
17296     public static List<String> readLines(InputStream stream) throws IOException {
17297         return IOGroovyMethods.readLines(stream);
17298     }
17299 
17300     @Deprecated
17301     public static List<String> readLines(InputStream stream, String charset) throws IOException {
17302         return IOGroovyMethods.readLines(stream, charset);
17303     }
17304 
17305     @Deprecated
17306     public static List<String> readLines(URL self) throws IOException {
17307         return ResourceGroovyMethods.readLines(self);
17308     }
17309 
17310     @Deprecated
17311     public static List<String> readLines(URL self, String charset) throws IOException {
17312         return ResourceGroovyMethods.readLines(self, charset);
17313     }
17314 
17315     @Deprecated
17316     public static List<String> readLines(Reader reader) throws IOException {
17317         return IOGroovyMethods.readLines(reader);
17318     }
17319 
17320     @Deprecated
17321     public static String getText(File file, String charset) throws IOException {
17322         return ResourceGroovyMethods.getText(file, charset);
17323     }
17324 
17325     @Deprecated
17326     public static String getText(File file) throws IOException {
17327         return ResourceGroovyMethods.getText(file);
17328     }
17329 
17330     @Deprecated
17331     public static String getText(URL url) throws IOException {
17332         return ResourceGroovyMethods.getText(url);
17333     }
17334 
17335     @Deprecated
17336     public static String getText(URL url, Map parameters) throws IOException {
17337         return ResourceGroovyMethods.getText(url, parameters);
17338     }
17339 
17340     @Deprecated
17341     public static String getText(URL url, String charset) throws IOException {
17342         return ResourceGroovyMethods.getText(url, charset);
17343     }
17344 
17345     @Deprecated
17346     public static String getText(URL url, Map parameters, String charset) throws IOException {
17347         return ResourceGroovyMethods.getText(url, parameters, charset);
17348     }
17349 
17350     @Deprecated
17351     public static String getText(InputStream is) throws IOException {
17352         return IOGroovyMethods.getText(is);
17353     }
17354 
17355     @Deprecated
17356     public static String getText(InputStream is, String charset) throws IOException {
17357         return IOGroovyMethods.getText(is, charset);
17358     }
17359 
17360     @Deprecated
17361     public static String getText(Reader reader) throws IOException {
17362         return IOGroovyMethods.getText(reader);
17363     }
17364 
17365     @Deprecated
17366     public static String getText(BufferedReader reader) throws IOException {
17367         return IOGroovyMethods.getText(reader);
17368     }
17369 
17370     @Deprecated
17371     public static byte[] getBytes(File file) throws IOException {
17372         return ResourceGroovyMethods.getBytes(file);
17373     }
17374 
17375     @Deprecated
17376     public static byte[] getBytes(URL url) throws IOException {
17377         return ResourceGroovyMethods.getBytes(url);
17378     }
17379 
17380     @Deprecated
17381     public static byte[] getBytes(InputStream is) throws IOException {
17382         return IOGroovyMethods.getBytes(is);
17383     }
17384 
17385     @Deprecated
17386     public static void setBytes(File file, byte[] bytes) throws IOException {
17387         ResourceGroovyMethods.setBytes(file, bytes);
17388     }
17389 
17390     @Deprecated
17391     public static void setBytes(OutputStream os, byte[] bytes) throws IOException {
17392         IOGroovyMethods.setBytes(os, bytes);
17393     }
17394 
17395     @Deprecated
17396     public static void writeLine(BufferedWriter writer, String line) throws IOException {
17397         IOGroovyMethods.writeLine(writer, line);
17398     }
17399 
17400     @Deprecated
17401     public static void write(File file, String text) throws IOException {
17402         ResourceGroovyMethods.write(file, text);
17403     }
17404 
17405     @Deprecated
17406     public static void setText(File file, String text) throws IOException {
17407         ResourceGroovyMethods.setText(file, text);
17408     }
17409 
17410     @Deprecated
17411     public static void setText(File file, String text, String charset) throws IOException {
17412         ResourceGroovyMethods.setText(file, text, charset);
17413     }
17414 
17415     @Deprecated
17416     public static File leftShift(File file, Object text) throws IOException {
17417         return ResourceGroovyMethods.leftShift(file, text);
17418     }
17419 
17420     @Deprecated
17421     public static File leftShift(File file, byte[] bytes) throws IOException {
17422         return ResourceGroovyMethods.leftShift(file, bytes);
17423     }
17424 
17425     @Deprecated
17426     public static File leftShift(File file, InputStream data) throws IOException {
17427         return ResourceGroovyMethods.leftShift(file, data);
17428     }
17429 
17430     @Deprecated
17431     public static void write(File file, String text, String charset) throws IOException {
17432         ResourceGroovyMethods.write(file, text, charset);
17433     }
17434 
17435     @Deprecated
17436     public static void append(File file, Object text) throws IOException {
17437         ResourceGroovyMethods.append(file, text);
17438     }
17439 
17440     @Deprecated
17441     public static void append(File file, byte[] bytes) throws IOException {
17442         ResourceGroovyMethods.append(file, bytes);
17443     }
17444 
17445     @Deprecated
17446     public static void append(File self, InputStream stream ) throws IOException {
17447         ResourceGroovyMethods.append(self, stream);
17448     }
17449 
17450     @Deprecated
17451     public static void append(File file, Object text, String charset) throws IOException {
17452         ResourceGroovyMethods.append(file, text, charset);
17453     }
17454 
17455     @Deprecated
17456     public static void eachFile(final File self, final FileType fileType, final Closure closure)
17457             throws FileNotFoundException, IllegalArgumentException {
17458         ResourceGroovyMethods.eachFile(self, fileType, closure);
17459     }
17460 
17461     @Deprecated
17462     public static void eachFile(final File self, final Closure closure) throws FileNotFoundException, IllegalArgumentException {
17463         ResourceGroovyMethods.eachFile(self, closure);
17464     }
17465 
17466     @Deprecated
17467     public static void eachDir(File self, Closure closure) throws FileNotFoundException, IllegalArgumentException {
17468         ResourceGroovyMethods.eachDir(self, closure);
17469     }
17470 
17471     @Deprecated
17472     public static void eachFileRecurse(final File self, final FileType fileType, final Closure closure)
17473             throws FileNotFoundException, IllegalArgumentException {
17474         ResourceGroovyMethods.eachFileRecurse(self, fileType, closure);
17475     }
17476 
17477     @Deprecated
17478     public static void traverse(final File self, final Map<String, Object> options, final Closure closure)
17479             throws FileNotFoundException, IllegalArgumentException {
17480         ResourceGroovyMethods.traverse(self, options, closure);
17481     }
17482 
17483     @Deprecated
17484     public static void traverse(final File self, final Closure closure) throws FileNotFoundException, IllegalArgumentException {
17485         ResourceGroovyMethods.traverse(self, closure);
17486     }
17487 
17488     @Deprecated
17489     public static void traverse(final File self, final Map<String, Object> options)
17490             throws FileNotFoundException, IllegalArgumentException {
17491         ResourceGroovyMethods.traverse(self, options);
17492     }
17493 
17494     @Deprecated
17495     public static void eachFileRecurse(File self, Closure closure) throws FileNotFoundException, IllegalArgumentException {
17496         ResourceGroovyMethods.eachFileRecurse(self, closure);
17497     }
17498 
17499     @Deprecated
17500     public static void eachDirRecurse(final File self, final Closure closure) throws FileNotFoundException, IllegalArgumentException {
17501         ResourceGroovyMethods.eachDirRecurse(self, closure);
17502     }
17503 
17504     @Deprecated
17505     public static void eachFileMatch(final File self, final FileType fileType, final Object nameFilter, final Closure closure)
17506             throws FileNotFoundException, IllegalArgumentException {
17507         ResourceGroovyMethods.eachFileMatch(self, fileType, nameFilter, closure);
17508     }
17509 
17510     @Deprecated
17511     public static void eachFileMatch(final File self, final Object nameFilter, final Closure closure)
17512             throws FileNotFoundException, IllegalArgumentException {
17513         ResourceGroovyMethods.eachFileMatch(self, nameFilter, closure);
17514     }
17515 
17516     @Deprecated
17517     public static void eachDirMatch(final File self, final Object nameFilter, final Closure closure) throws FileNotFoundException, IllegalArgumentException {
17518         ResourceGroovyMethods.eachDirMatch(self, nameFilter, closure);
17519     }
17520 
17521     @Deprecated
17522     public static boolean deleteDir(final File self) {
17523         return ResourceGroovyMethods.deleteDir(self);
17524     }
17525 
17526     @Deprecated
17527     public static boolean renameTo(final File self, String newPathName) {
17528         return ResourceGroovyMethods.renameTo(self, newPathName);
17529     }
17530 
17531     @Deprecated
17532     public static Iterator<String> iterator(Reader self) {
17533         return IOGroovyMethods.iterator(self);
17534     }
17535 
17536     @Deprecated
17537     public static Iterator<Byte> iterator(InputStream self) {
17538         return IOGroovyMethods.iterator(self);
17539     }
17540 
17541     @Deprecated
17542     public static Iterator<Byte> iterator(final DataInputStream self) {
17543         return IOGroovyMethods.iterator(self);
17544     }
17545 
17546     @Deprecated
17547     public static File asWritable(File file) {
17548         return ResourceGroovyMethods.asWritable(file);
17549     }
17550 
17551     @Deprecated
17552     public static <T> T asType(File f, Class<T> c) {
17553         return ResourceGroovyMethods.asType(f, c);
17554     }
17555 
17556     @Deprecated
17557     public static File asWritable(File file, String encoding) {
17558         return ResourceGroovyMethods.asWritable(file, encoding);
17559     }
17560 
17561     @Deprecated
17562     public static BufferedReader newReader(File file) throws IOException {
17563         return ResourceGroovyMethods.newReader(file);
17564     }
17565 
17566     @Deprecated
17567     public static BufferedReader newReader(File file, String charset)
17568             throws FileNotFoundException, UnsupportedEncodingException {
17569         return ResourceGroovyMethods.newReader(file, charset);
17570     }
17571 
17572     @Deprecated
17573     public static BufferedReader newReader(InputStream self) {
17574         return IOGroovyMethods.newReader(self);
17575     }
17576 
17577     @Deprecated
17578     public static BufferedReader newReader(InputStream self, String charset) throws UnsupportedEncodingException {
17579         return IOGroovyMethods.newReader(self, charset);
17580     }
17581 
17582     @Deprecated
17583     public static <T> T withReader(File file, Closure<T> closure) throws IOException {
17584         return ResourceGroovyMethods.withReader(file, closure);
17585     }
17586 
17587     @Deprecated
17588     public static <T> T withReader(File file, String charset, Closure<T> closure) throws IOException {
17589         return ResourceGroovyMethods.withReader(file, charset, closure);
17590     }
17591 
17592     @Deprecated
17593     public static BufferedOutputStream newOutputStream(File file) throws IOException {
17594         return ResourceGroovyMethods.newOutputStream(file);
17595     }
17596 
17597     @Deprecated
17598     public static DataOutputStream newDataOutputStream(File file) throws IOException {
17599         return ResourceGroovyMethods.newDataOutputStream(file);
17600     }
17601 
17602     @Deprecated
17603     public static Object withOutputStream(File file, Closure closure) throws IOException {
17604         return ResourceGroovyMethods.withOutputStream(file, closure);
17605     }
17606 
17607     @Deprecated
17608     public static Object withInputStream(File file, Closure closure) throws IOException {
17609         return ResourceGroovyMethods.withInputStream(file, closure);
17610     }
17611 
17612     @Deprecated
17613     public static <T> T withInputStream(URL url, Closure<T> closure) throws IOException {
17614         return ResourceGroovyMethods.withInputStream(url, closure);
17615     }
17616 
17617     @Deprecated
17618     public static <T> T withDataOutputStream(File file, Closure<T> closure) throws IOException {
17619         return ResourceGroovyMethods.withDataOutputStream(file, closure);
17620     }
17621 
17622     @Deprecated
17623     public static <T> T withDataInputStream(File file, Closure<T> closure) throws IOException {
17624         return ResourceGroovyMethods.withDataInputStream(file, closure);
17625     }
17626 
17627     @Deprecated
17628     public static BufferedWriter newWriter(File file) throws IOException {
17629         return ResourceGroovyMethods.newWriter(file);
17630     }
17631 
17632     @Deprecated
17633     public static BufferedWriter newWriter(File file, boolean append) throws IOException {
17634         return ResourceGroovyMethods.newWriter(file, append);
17635     }
17636 
17637     @Deprecated
17638     public static BufferedWriter newWriter(File file, String charset, boolean append) throws IOException {
17639         return ResourceGroovyMethods.newWriter(file, charset, append);
17640     }
17641 
17642     @Deprecated
17643     public static BufferedWriter newWriter(File file, String charset) throws IOException {
17644         return ResourceGroovyMethods.newWriter(file, charset);
17645     }
17646 
17647     @Deprecated
17648     public static <T> T withWriter(File file, Closure<T> closure) throws IOException {
17649         return ResourceGroovyMethods.withWriter(file, closure);
17650     }
17651 
17652     @Deprecated
17653     public static <T> T withWriter(File file, String charset, Closure<T> closure) throws IOException {
17654         return ResourceGroovyMethods.withWriter(file, charset, closure);
17655     }
17656 
17657     @Deprecated
17658     public static <T> T withWriterAppend(File file, String charset, Closure<T> closure) throws IOException {
17659         return ResourceGroovyMethods.withWriterAppend(file, charset, closure);
17660     }
17661 
17662     @Deprecated
17663     public static <T> T withWriterAppend(File file, Closure<T> closure) throws IOException {
17664         return ResourceGroovyMethods.withWriterAppend(file, closure);
17665     }
17666 
17667     @Deprecated
17668     public static PrintWriter newPrintWriter(File file) throws IOException {
17669         return ResourceGroovyMethods.newPrintWriter(file);
17670     }
17671 
17672     @Deprecated
17673     public static PrintWriter newPrintWriter(File file, String charset) throws IOException {
17674         return ResourceGroovyMethods.newPrintWriter(file, charset);
17675     }
17676 
17677     @Deprecated
17678     public static PrintWriter newPrintWriter(Writer writer) {
17679         return IOGroovyMethods.newPrintWriter(writer);
17680     }
17681 
17682     @Deprecated
17683     public static <T> T withPrintWriter(File file, Closure<T> closure) throws IOException {
17684         return ResourceGroovyMethods.withPrintWriter(file, closure);
17685     }
17686 
17687     @Deprecated
17688     public static <T> T withPrintWriter(File file, String charset, Closure<T> closure) throws IOException {
17689         return ResourceGroovyMethods.withPrintWriter(file, charset, closure);
17690     }
17691 
17692     @Deprecated
17693     public static <T> T withPrintWriter(Writer writer, Closure<T> closure) throws IOException {
17694         return IOGroovyMethods.withPrintWriter(writer, closure);
17695     }
17696 
17697     @Deprecated
17698     public static <T> T withWriter(Writer writer, Closure<T> closure) throws IOException {
17699         return IOGroovyMethods.withWriter(writer, closure);
17700     }
17701 
17702     @Deprecated
17703     public static <T> T withReader(Reader reader, Closure<T> closure) throws IOException {
17704         return IOGroovyMethods.withReader(reader, closure);
17705     }
17706 
17707     @Deprecated
17708     public static <T> T withStream(InputStream stream, Closure<T> closure) throws IOException {
17709         return IOGroovyMethods.withStream(stream, closure);
17710     }
17711 
17712     @Deprecated
17713     public static <T> T withReader(URL url, Closure<T> closure) throws IOException {
17714         return ResourceGroovyMethods.withReader(url, closure);
17715     }
17716 
17717     @Deprecated
17718     public static <T> T withReader(URL url, String charset, Closure<T> closure) throws IOException {
17719         return ResourceGroovyMethods.withReader(url, charset, closure);
17720     }
17721 
17722     @Deprecated
17723     public static <T> T withReader(InputStream in, Closure<T> closure) throws IOException {
17724         return IOGroovyMethods.withReader(in, closure);
17725     }
17726 
17727     @Deprecated
17728     public static <T> T withReader(InputStream in, String charset, Closure<T> closure) throws IOException {
17729         return IOGroovyMethods.withReader(in, charset, closure);
17730     }
17731 
17732     @Deprecated
17733     public static <T> T withWriter(OutputStream stream, Closure<T> closure) throws IOException {
17734         return IOGroovyMethods.withWriter(stream, closure);
17735     }
17736 
17737     @Deprecated
17738     public static <T> T withWriter(OutputStream stream, String charset, Closure<T> closure) throws IOException {
17739         return IOGroovyMethods.withWriter(stream, charset, closure);
17740     }
17741 
17742     @Deprecated
17743     public static <T> T withStream(OutputStream os, Closure<T> closure) throws IOException {
17744         return IOGroovyMethods.withStream(os, closure);
17745     }
17746 
17747     @Deprecated
17748     public static BufferedInputStream newInputStream(File file) throws FileNotFoundException {
17749         return ResourceGroovyMethods.newInputStream(file);
17750     }
17751 
17752     @Deprecated
17753     public static BufferedInputStream newInputStream(URL url) throws MalformedURLException, IOException {
17754         return ResourceGroovyMethods.newInputStream(url);
17755     }
17756 
17757     @Deprecated
17758     public static BufferedInputStream newInputStream(URL url, Map parameters) throws MalformedURLException, IOException {
17759         return ResourceGroovyMethods.newInputStream(url, parameters);
17760     }
17761 
17762     @Deprecated
17763     public static BufferedReader newReader(URL url) throws MalformedURLException, IOException {
17764         return ResourceGroovyMethods.newReader(url);
17765     }
17766 
17767     @Deprecated
17768     public static BufferedReader newReader(URL url, Map parameters) throws MalformedURLException, IOException {
17769         return ResourceGroovyMethods.newReader(url, parameters);
17770     }
17771 
17772     @Deprecated
17773     public static BufferedReader newReader(URL url, String charset) throws MalformedURLException, IOException {
17774         return ResourceGroovyMethods.newReader(url, charset);
17775     }
17776 
17777     @Deprecated
17778     public static BufferedReader newReader(URL url, Map parameters, String charset) throws MalformedURLException, IOException {
17779         return ResourceGroovyMethods.newReader(url, parameters, charset);
17780     }
17781 
17782     @Deprecated
17783     public static DataInputStream newDataInputStream(File file) throws FileNotFoundException {
17784         return ResourceGroovyMethods.newDataInputStream(file);
17785     }
17786 
17787     @Deprecated
17788     public static void eachByte(File self, Closure closure) throws IOException {
17789         ResourceGroovyMethods.eachByte(self, closure);
17790     }
17791 
17792     @Deprecated
17793     public static void eachByte(File self, int bufferLen, Closure closure) throws IOException {
17794         ResourceGroovyMethods.eachByte(self, bufferLen, closure);
17795     }
17796 
17797     @Deprecated
17798     public static void eachByte(InputStream is, Closure closure) throws IOException {
17799         IOGroovyMethods.eachByte(is, closure);
17800     }
17801 
17802     @Deprecated
17803     public static void eachByte(InputStream is, int bufferLen, Closure closure) throws IOException {
17804         IOGroovyMethods.eachByte(is, bufferLen, closure);
17805     }
17806 
17807     @Deprecated
17808     public static void eachByte(URL url, Closure closure) throws IOException {
17809         ResourceGroovyMethods.eachByte(url, closure);
17810     }
17811 
17812     @Deprecated
17813     public static void eachByte(URL url, int bufferLen, Closure closure) throws IOException {
17814         ResourceGroovyMethods.eachByte(url, bufferLen, closure);
17815     }
17816 
17817     @Deprecated
17818     public static void transformChar(Reader self, Writer writer, Closure closure) throws IOException {
17819         IOGroovyMethods.transformChar(self, writer, closure);
17820     }
17821 
17822     @Deprecated
17823     public static void transformLine(Reader reader, Writer writer, Closure closure) throws IOException {
17824         IOGroovyMethods.transformLine(reader, writer, closure);
17825     }
17826 
17827     @Deprecated
17828     public static void filterLine(Reader reader, Writer writer, Closure closure) throws IOException {
17829         IOGroovyMethods.filterLine(reader, writer, closure);
17830     }
17831 
17832     @Deprecated
17833     public static Writable filterLine(File self, Closure closure) throws IOException {
17834         return ResourceGroovyMethods.filterLine(self, closure);
17835     }
17836 
17837     @Deprecated
17838     public static Writable filterLine(File self, String charset, Closure closure) throws IOException {
17839         return ResourceGroovyMethods.filterLine(self, closure);
17840     }
17841 
17842     @Deprecated
17843     public static void filterLine(File self, Writer writer, Closure closure) throws IOException {
17844         ResourceGroovyMethods.filterLine(self, writer, closure);
17845     }
17846 
17847     @Deprecated
17848     public static void filterLine(File self, Writer writer, String charset, Closure closure) throws IOException {
17849         ResourceGroovyMethods.filterLine(self, writer, charset, closure);
17850     }
17851 
17852     @Deprecated
17853     public static Writable filterLine(Reader reader, final Closure closure) {
17854         return IOGroovyMethods.filterLine(reader, closure);
17855     }
17856 
17857     @Deprecated
17858     public static Writable filterLine(InputStream self, Closure predicate) {
17859         return IOGroovyMethods.filterLine(self, predicate);
17860     }
17861 
17862     @Deprecated
17863     public static Writable filterLine(InputStream self, String charset, Closure predicate) throws UnsupportedEncodingException {
17864         return IOGroovyMethods.filterLine(self, charset, predicate);
17865     }
17866 
17867     @Deprecated
17868     public static void filterLine(InputStream self, Writer writer, Closure predicate) throws IOException {
17869         IOGroovyMethods.filterLine(self, writer, predicate);
17870     }
17871 
17872     @Deprecated
17873     public static void filterLine(InputStream self, Writer writer, String charset, Closure predicate) throws IOException {
17874         IOGroovyMethods.filterLine(self, writer, charset, predicate);
17875     }
17876 
17877     @Deprecated
17878     public static Writable filterLine(URL self, Closure predicate) throws IOException {
17879         return ResourceGroovyMethods.filterLine(self, predicate);
17880     }
17881 
17882     @Deprecated
17883     public static Writable filterLine(URL self, String charset, Closure predicate) throws IOException {
17884         return ResourceGroovyMethods.filterLine(self, charset, predicate);
17885     }
17886 
17887     @Deprecated
17888     public static void filterLine(URL self, Writer writer, Closure predicate) throws IOException {
17889         ResourceGroovyMethods.filterLine(self, writer, predicate);
17890     }
17891 
17892     @Deprecated
17893     public static void filterLine(URL self, Writer writer, String charset, Closure predicate) throws IOException {
17894         ResourceGroovyMethods.filterLine(self, writer, charset, predicate);
17895     }
17896 
17897     @Deprecated
17898     public static byte[] readBytes(File file) throws IOException {
17899         return ResourceGroovyMethods.readBytes(file);
17900     }
17901 
17902     /**
17903      * Dynamically wraps an instance into something which implements the
17904      * supplied trait classes. It is guaranteed that the returned object
17905      * will implement the trait interfaces, but the original type of the
17906      * object is lost (replaced with a proxy).
17907      * @param self object to be wrapped
17908      * @param traits a list of trait classes
17909      * @return a proxy implementing the trait interfaces
17910      */
17911     public static Object withTraits(Object self, Class<?>... traits) {
17912         List<Class> interfaces = new ArrayList<Class>();
17913         Collections.addAll(interfaces, traits);
17914         return ProxyGenerator.INSTANCE.instantiateDelegate(interfaces, self);
17915     }
17916 
17917     /**
17918      * Swaps two elements at the specified positions.
17919      * <p>
17920      * Example:
17921      * <pre class="groovyTestCase">
17922      * assert [1, 3, 2, 4] == [1, 2, 3, 4].swap(1, 2)
17923      * </pre>
17924      *
17925      * @param self a List
17926      * @param i a position
17927      * @param j a position
17928      * @return self
17929      * @see Collections#swap(List, int, int)
17930      * @since 2.4.0
17931      */
17932     public static <T> List<T> swap(List<T> self, int i, int j) {
17933         Collections.swap(self, i, j);
17934         return self;
17935     }
17936 
17937     /**
17938      * Swaps two elements at the specified positions.
17939      * <p>
17940      * Example:
17941      * <pre class="groovyTestCase">
17942      * assert (["a", "c", "b", "d"] as String[]) == (["a", "b", "c", "d"] as String[]).swap(1, 2)
17943      * </pre>
17944      *
17945      * @param self an array
17946      * @param i a position
17947      * @param j a position
17948      * @return self
17949      * @since 2.4.0
17950      */
17951     public static <T> T[] swap(T[] self, int i, int j) {
17952         T tmp = self[i];
17953         self[i] = self[j];
17954         self[j] = tmp;
17955         return self;
17956     }
17957 
17958     /**
17959      * Swaps two elements at the specified positions.
17960      * <p>
17961      * Example:
17962      * <pre class="groovyTestCase">
17963      * assert ([false, true, false, true] as boolean[]) == ([false, false, true, true] as boolean[]).swap(1, 2)
17964      * </pre>
17965      *
17966      * @param self a boolean array
17967      * @param i a position
17968      * @param j a position
17969      * @return self
17970      * @since 2.4.0
17971      */
17972     public static boolean[] swap(boolean[] self, int i, int j) {
17973         boolean tmp = self[i];
17974         self[i] = self[j];
17975         self[j] = tmp;
17976         return self;
17977     }
17978 
17979     /**
17980      * Swaps two elements at the specified positions.
17981      * <p>
17982      * Example:
17983      * <pre class="groovyTestCase">
17984      * assert ([1, 3, 2, 4] as byte[]) == ([1, 2, 3, 4] as byte[]).swap(1, 2)
17985      * </pre>
17986      *
17987      * @param self a boolean array
17988      * @param i a position
17989      * @param j a position
17990      * @return self
17991      * @since 2.4.0
17992      */
17993     public static byte[] swap(byte[] self, int i, int j) {
17994         byte tmp = self[i];
17995         self[i] = self[j];
17996         self[j] = tmp;
17997         return self;
17998     }
17999 
18000     /**
18001      * Swaps two elements at the specified positions.
18002      * <p>
18003      * Example:
18004      * <pre class="groovyTestCase">
18005      * assert ([1, 3, 2, 4] as char[]) == ([1, 2, 3, 4] as char[]).swap(1, 2)
18006      * </pre>
18007      *
18008      * @param self a boolean array
18009      * @param i a position
18010      * @param j a position
18011      * @return self
18012      * @since 2.4.0
18013      */
18014     public static char[] swap(char[] self, int i, int j) {
18015         char tmp = self[i];
18016         self[i] = self[j];
18017         self[j] = tmp;
18018         return self;
18019     }
18020 
18021     /**
18022      * Swaps two elements at the specified positions.
18023      * <p>
18024      * Example:
18025      * <pre class="groovyTestCase">
18026      * assert ([1, 3, 2, 4] as double[]) == ([1, 2, 3, 4] as double[]).swap(1, 2)
18027      * </pre>
18028      *
18029      * @param self a boolean array
18030      * @param i a position
18031      * @param j a position
18032      * @return self
18033      * @since 2.4.0
18034      */
18035     public static double[] swap(double[] self, int i, int j) {
18036         double tmp = self[i];
18037         self[i] = self[j];
18038         self[j] = tmp;
18039         return self;
18040     }
18041 
18042     /**
18043      * Swaps two elements at the specified positions.
18044      * <p>
18045      * Example:
18046      * <pre class="groovyTestCase">
18047      * assert ([1, 3, 2, 4] as float[]) == ([1, 2, 3, 4] as float[]).swap(1, 2)
18048      * </pre>
18049      *
18050      * @param self a boolean array
18051      * @param i a position
18052      * @param j a position
18053      * @return self
18054      * @since 2.4.0
18055      */
18056     public static float[] swap(float[] self, int i, int j) {
18057         float tmp = self[i];
18058         self[i] = self[j];
18059         self[j] = tmp;
18060         return self;
18061     }
18062 
18063     /**
18064      * Swaps two elements at the specified positions.
18065      * <p>
18066      * Example:
18067      * <pre class="groovyTestCase">
18068      * assert ([1, 3, 2, 4] as int[]) == ([1, 2, 3, 4] as int[]).swap(1, 2)
18069      * </pre>
18070      *
18071      * @param self a boolean array
18072      * @param i a position
18073      * @param j a position
18074      * @return self
18075      * @since 2.4.0
18076      */
18077     public static int[] swap(int[] self, int i, int j) {
18078         int tmp = self[i];
18079         self[i] = self[j];
18080         self[j] = tmp;
18081         return self;
18082     }
18083 
18084     /**
18085      * Swaps two elements at the specified positions.
18086      * <p>
18087      * Example:
18088      * <pre class="groovyTestCase">
18089      * assert ([1, 3, 2, 4] as long[]) == ([1, 2, 3, 4] as long[]).swap(1, 2)
18090      * </pre>
18091      *
18092      * @param self a boolean array
18093      * @param i a position
18094      * @param j a position
18095      * @return self
18096      * @since 2.4.0
18097      */
18098     public static long[] swap(long[] self, int i, int j) {
18099         long tmp = self[i];
18100         self[i] = self[j];
18101         self[j] = tmp;
18102         return self;
18103     }
18104 
18105     /**
18106      * Swaps two elements at the specified positions.
18107      * <p>
18108      * Example:
18109      * <pre class="groovyTestCase">
18110      * assert ([1, 3, 2, 4] as short[]) == ([1, 2, 3, 4] as short[]).swap(1, 2)
18111      * </pre>
18112      *
18113      * @param self a boolean array
18114      * @param i a position
18115      * @param j a position
18116      * @return self
18117      * @since 2.4.0
18118      */
18119     public static short[] swap(short[] self, int i, int j) {
18120         short tmp = self[i];
18121         self[i] = self[j];
18122         self[j] = tmp;
18123         return self;
18124     }
18125 
18126     /**
18127      * Modifies this list by removing the element at the specified position
18128      * in this list. Returns the removed element. Essentially an alias for
18129      * {@link List#remove(int)} but with no ambiguity for List&lt;Integer&gt;.
18130      * <p/>
18131      * Example:
18132      * <pre class="groovyTestCase">
18133      * def list = [1, 2, 3]
18134      * list.removeAt(1)
18135      * assert [1, 3] == list
18136      * </pre>
18137      *
18138      * @param self a List
18139      * @param index the index of the element to be removed
18140      * @return the element previously at the specified position
18141      * @since 2.4.0
18142      */
18143     public static <E> E removeAt(List<E> self, int index) {
18144         return self.remove(index);
18145     }
18146 
18147     /**
18148      * Modifies this collection by removing a single instance of the specified
18149      * element from this collection, if it is present. Essentially an alias for
18150      * {@link Collection#remove(Object)} but with no ambiguity for Collection&lt;Integer&gt;.
18151      * <p/>
18152      * Example:
18153      * <pre class="groovyTestCase">
18154      * def list = [1, 2, 3, 2]
18155      * list.removeElement(2)
18156      * assert [1, 3, 2] == list
18157      * </pre>
18158      *
18159      * @param self a Collection
18160      * @param o element to be removed from this collection, if present
18161      * @return true if an element was removed as a result of this call
18162      * @since 2.4.0
18163      */
18164     public static <E> boolean removeElement(Collection<E> self, Object o) {
18165         return self.remove(o);
18166     }
18167 }